Beispiel #1
0
/**
 * Obfuscate the given text using HTML entity encoding.
 *
 * @param  string		The text to obfuscate
 * @return string		The obfuscated version
 */
function obfuscate_entities($val)
{
    if (strpos($val, '&') !== false) {
        return $val;
    }
    // Prevent double encoding
    $out = '';
    for ($i = 0; $i < strlen($val); $i++) {
        $char = $val[$i];
        if ($char == '<') {
            $_char = '&lt;';
        } elseif ($char == '>') {
            $_char = '&gt;';
        } elseif ($char == '&') {
            $_char = '&amp;';
        } elseif ($i % 2 == 0) {
            $_char = '&#' . sprintf('%d', ord($char)) . ';';
        } else {
            $_char = '&#x' . sprintf('%x', ord($char)) . ';';
        }
        $out .= $_char;
    }
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($out);
    }
    return $out;
}
Beispiel #2
0
/**
 * Get information about new versions of ocPortal (or more accurately, what's wrong with this version).
 *
 * @return tempcode		Information about the installed ocPortal version
 */
function get_future_version_information()
{
    require_lang('version');
    $url = 'http://ocportal.com/version.php?version=' . rawurlencode(ocp_version_full()) . '&lang=' . rawurlencode(user_lang());
    $data = http_download_file($url, NULL, false);
    if (!is_null($data)) {
        $data = str_replace('"../upgrader.php"', '"' . get_base_url() . '/upgrader.php"', $data);
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($data);
        }
        require_code('character_sets');
        $data = convert_to_internal_encoding($data);
        $table = new ocp_tempcode();
        $lines = explode(chr(10), $data);
        foreach ($lines as $line) {
            if (trim($line) != '') {
                $table->attach(paragraph($line));
            }
        }
        $table = make_string_tempcode(preg_replace('#<p>\\s*</p>#', '', $table->evaluate()));
    } else {
        $table = paragraph(do_lang_tempcode('CANNOT_CONNECT_HOME'), 'dfsdff32ffd');
    }
    require_code('xhtml');
    /*$table->attach('<script type="text/javascript">// <![CDATA[
    		window.open(\''.$url.'\');
    	//]]></script>');*/
    return make_string_tempcode(xhtmlise_html($table->evaluate()));
}
Beispiel #3
0
/**
 * URL'ise specially encoded text-acceptance language strings.
 *
 * @param  string			The language string
 * @param  mixed			The URL (either tempcode or string)
 * @param  string			The title of the hyperlink
 * @param  boolean		Whether to use a new window
 * @return tempcode		The encoded version
 */
function _urlise_lang($string, $url, $title, $new_window)
{
    $a = strpos($string, '<{');
    $b = strpos($string, '}>');
    if ($a === false || $b === false || $b < $a) {
        return make_string_tempcode($string);
    }
    $section = substr($string, $a + 2, $b - $a - 2);
    $prior = substr($string, 0, $a);
    $after = substr($string, $b + 2);
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($section);
        ocp_mark_as_escaped($prior);
        ocp_mark_as_escaped($after);
    }
    if (is_string($url)) {
        if ($url == '') {
            return protect_from_escaping($section);
        }
    } else {
        if ($url->is_empty()) {
            return protect_from_escaping($section);
        }
    }
    $out = new ocp_tempcode();
    $out->attach(protect_from_escaping($prior));
    $out->attach(hyperlink($url, protect_from_escaping($section), $new_window, false, $title));
    $out->attach(protect_from_escaping($after));
    return $out;
}
Beispiel #4
0
/**
 * Get the symbol of the currency we're trading in.
 *
 * @return ID_TEXT	The currency.
 */
function ecommerce_get_currency_symbol()
{
    $currency = get_option('currency');
    switch ($currency) {
        case 'USD':
            $currency = '$';
            break;
        case 'CAD':
            $currency = '$';
            break;
        case 'EUR':
            $currency = '&euro;';
            break;
        case 'GBP':
            $currency = '&pound;';
            break;
        case 'JPY':
            $currency = '&yen;';
            break;
        case 'AUD':
            $currency = '$';
            break;
    }
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($currency);
    }
    return $currency;
}
Beispiel #5
0
function _diff_simple($old, $new, $unified = false)
{
    $diff = new Text_Diff($old, $new);
    if ($unified) {
        $renderer = new Text_Diff_Renderer_unified();
    } else {
        $renderer = new Text_Diff_Renderer_inline();
    }
    $diff_html = $rendered_diff = $renderer->render($diff);
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($diff_html);
    }
    return $diff_html;
}
Beispiel #6
0
    /**
     * Standard modular run function. Creates custom graphics from parameters.
     *
     * @param  array		Map of hook parameters (relayed from block parameters map).
     * @param  object		The block itself (contains utility methods).
     * @return tempcode	HTML to output.
     */
    function run($map, &$block)
    {
        if (!function_exists('imagettftext') || !array_key_exists('FreeType Support', gd_info()) || @imagettfbbox(26.0, 0.0, get_file_base() . '/data/fonts/Vera.ttf', 'test') === false) {
            return do_lang_tempcode('REQUIRES_TTF');
        }
        if (!array_key_exists('img1', $map)) {
            $map['img1'] = 'button1';
        }
        $img_path_1 = find_theme_image($map['img1'], true, true);
        if ($img_path_1 == '') {
            return do_lang_tempcode('NO_SUCH_THEME_IMAGE', $map['img1']);
        }
        $cache_id_1 = 'rollover1_' . md5(serialize($map));
        $url_1 = $block->_do_image($cache_id_1, $map, $img_path_1);
        if (is_object($url_1)) {
            return $url_1;
        }
        if (!array_key_exists('img2', $map)) {
            $map['img2'] = 'button2';
        }
        $img_path_2 = find_theme_image($map['img2'], true, true);
        if ($img_path_2 == '') {
            return do_lang_tempcode('NO_SUCH_THEME_IMAGE', $map['img2']);
        }
        $cache_id_2 = 'rollover2_' . md5(serialize($map));
        $url_2 = $block->_do_image($cache_id_2, $map, $img_path_2);
        if (is_object($url_2)) {
            return $url_2;
        }
        $comb_id = 'rollover_' . uniqid('', true);
        $ret = '<img id="' . php_addslashes($comb_id) . '" class="gfx_text_overlay" alt="' . str_replace(chr(10), ' ', escape_html($map['data'])) . '" src="' . escape_html($url_1) . '" />';
        $ret .= '
			<script type="text/javascript">// <![CDATA[
				create_rollover("' . php_addslashes($comb_id) . '","' . php_addslashes($url_2) . '");
			//]]></script>
		';
        if (function_exists('ocp_mark_as_escaped')) {
            ocp_mark_as_escaped($ret);
        }
        return make_string_tempcode($ret);
    }
Beispiel #7
0
 /**
  * Standard modular run function. Creates custom graphics from parameters.
  *
  * @param  array		Map of hook parameters (relayed from block parameters map).
  * @param  object		The block itself (contains utility methods).
  * @return tempcode	HTML to output.
  */
 function run($map, &$block)
 {
     if (!function_exists('imagettftext') || !array_key_exists('FreeType Support', gd_info()) || @imagettfbbox(26.0, 0.0, get_file_base() . '/data/fonts/Vera.ttf', 'test') === false) {
         return do_lang_tempcode('REQUIRES_TTF');
     }
     if (!array_key_exists('img', $map)) {
         $map['img'] = 'button1';
     }
     $img_path = find_theme_image($map['img'], true, true);
     if ($img_path == '') {
         return do_lang_tempcode('NO_SUCH_THEME_IMAGE', $map['img']);
     }
     $cache_id = 'text_overlay_' . md5(serialize($map));
     $url = $block->_do_image($cache_id, $map, $img_path);
     if (is_object($url)) {
         return $url;
     }
     $ret = '<img class="gfx_text_overlay" alt="' . str_replace(chr(10), ' ', escape_html($map['data'])) . '" src="' . escape_html($url) . '" />';
     if (function_exists('ocp_mark_as_escaped')) {
         ocp_mark_as_escaped($ret);
     }
     return make_string_tempcode($ret);
 }
Beispiel #8
0
/**
 * Get a nice, formatted XHTML list extending from the root, and showing all subcategories, and their subcategories (ad infinitum). The tree bit is because each entry in the list is shown to include the path through the tree that gets to it
 *
 * @param  ?AUTO_LINK	The currently selected category (NULL: none selected)
 * @param  boolean		Whether to make the list elements store comma-separated child lists instead of IDs
 * @param  boolean		Whether to only show for what may be added to by the current member
 * @return tempcode		The list of categories
 */
function nice_get_download_category_tree($it = NULL, $use_compound_list = false, $addable_filter = false)
{
    $tree = get_download_category_tree(NULL, NULL, NULL, false, $use_compound_list, NULL, $addable_filter);
    if ($use_compound_list) {
        $tree = $tree[0];
    }
    $out = '';
    // XHTMLXHTML
    foreach ($tree as $category) {
        if ($addable_filter && !$category['addable']) {
            continue;
        }
        $selected = $category['id'] == $it;
        $line = do_template('DOWNLOAD_LIST_LINE_2', array('_GUID' => '0ccffeff5b80b1840188b839aee8d9f2', 'TREE' => $category['tree'], 'FILECOUNT' => '?'));
        $out .= '<option value="' . (!$use_compound_list ? strval($category['id']) : $category['compound_list']) . '"' . ($selected ? ' selected="selected"' : '') . '>' . $line->evaluate() . '</option>';
    }
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($out);
    }
    return make_string_tempcode($out);
}
Beispiel #9
0
/**
 * Get a nice, formatted XHTML list of entries, in catalogue category tree structure
 *
 * @param  ID_TEXT		The catalogue name
 * @param  ?AUTO_LINK	The currently selected entry (NULL: none selected)
 * @param  ?AUTO_LINK	Only show entries submitted by this member (NULL: no filter)
 * @param  boolean		Whether to only show for what may be edited by the current member
 * @return tempcode		The list of entries
 */
function nice_get_catalogue_entries_tree($catalogue_name, $it = NULL, $submitter = NULL, $editable_filter = false)
{
    $tree = get_catalogue_entries_tree($catalogue_name, $submitter, NULL, NULL, NULL, NULL, $editable_filter);
    $out = '';
    // XHTMLXHTML
    foreach ($tree as $category) {
        foreach ($category['entries'] as $eid => $etitle) {
            $selected = $eid == $it;
            $line = do_template('CATALOGUE_ENTRIES_LIST_LINE', array('_GUID' => '0ccffeff5b80b1840188b83aaee8d9f2', 'TREE' => $category['tree'], 'NAME' => $etitle));
            $out .= '<option value="' . strval($eid) . '"' . ($selected ? 'selected="selected"' : '') . '>' . $line->evaluate() . '</option>';
        }
    }
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($out);
    }
    return make_string_tempcode($out);
}
Beispiel #10
0
/**
 * Generate a tempcode tree based selection list (ala nice_get_*) for choosing a forum OR a map of details. Also capable of getting comma-separated ancester forum lists. Also capable of displaying topic lists in the tree. In other words... this function is incredibly powerful, and complex.
 *
 * @param  ?MEMBER		The member that the view privileges are done for (NULL: current member).
 * @param  ?AUTO_LINK	The forum we are starting from (NULL: capture the whole tree).
 * @param  boolean		Whether to get a tempcode list (as opposed to a list of maps).
 * @param  ?array			The forum(s) to select by default (NULL: no preference). Only applies if !$topics_too. An array of AUTO_LINK's (for IDs) or strings (for names).
 * @param  string			The ancester list at this point of the recursion (blank for the start).
 * @param  ?AUTO_LINK	ID of a forum to skip display/recursion for (NULL: none).
 * @param  ?boolean		Whether the child forums are ordered alphabetically (NULL: find from DB).
 * @param  boolean		Whether to generate a compound list (a list of all the ancesters, for each point in the forum tree) as well as the tree.
 * @param  ?integer		The number of recursive levels to search (NULL: all)
 * @param  boolean		Whether to generate tree statistics.
 * @return mixed			Each tempcode of the tree if $field_format or else a list of maps, OR (if $use_compound_list) a pair of the tempcode and the compound list.
 */
function ocf_get_forum_tree_secure($member_id = NULL, $base_forum = NULL, $field_format = false, $selected_forum = NULL, $tree = '', $skip = NULL, $order_sub_alpha = NULL, $use_compound_list = false, $levels = NULL, $do_stats = false)
{
    if ($levels == -1 && !$use_compound_list) {
        return $use_compound_list ? array(array(), '') : array();
    }
    global $FORUM_TREE_SECURE_CACHE;
    if (is_null($member_id)) {
        $member_id = get_member();
    }
    if (is_null($order_sub_alpha)) {
        if (is_null($base_forum)) {
            $order_sub_alpha = false;
        } else {
            $order_sub_alpha = $GLOBALS['FORUM_DB']->query_value('f_forums', 'f_order_sub_alpha', array('id' => $base_forum));
        }
    }
    $out = array();
    $order = $order_sub_alpha ? 'f_name' : 'f_position,id';
    $forums = array();
    if (is_null($FORUM_TREE_SECURE_CACHE)) {
        $FORUM_TREE_SECURE_CACHE = mixed();
        $num_forums = $GLOBALS['FORUM_DB']->query_value('f_forums', 'COUNT(*)');
        $FORUM_TREE_SECURE_CACHE = $num_forums >= 300;
        // Mark it as 'huge'
    }
    if ($FORUM_TREE_SECURE_CACHE === true) {
        $forums = $GLOBALS['FORUM_DB']->query('SELECT id,f_order_sub_alpha,f_name,f_category_id,f_parent_forum,f_position FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_forums WHERE id IS NOT NULL AND ' . db_string_equal_to('f_redirection', '') . ' AND ' . (is_null($base_forum) ? 'f_parent_forum IS NULL' : 'f_parent_forum=' . strval($base_forum)) . ' ORDER BY f_position', 200);
    } else {
        if (is_null($FORUM_TREE_SECURE_CACHE) || $FORUM_TREE_SECURE_CACHE === false) {
            $FORUM_TREE_SECURE_CACHE = $GLOBALS['FORUM_DB']->query('SELECT id,f_order_sub_alpha,f_name,f_category_id,f_parent_forum,f_position FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_forums WHERE id IS NOT NULL AND ' . db_string_equal_to('f_redirection', '') . ' ORDER BY f_position');
        }
        foreach ($FORUM_TREE_SECURE_CACHE as $x) {
            if ($x['f_parent_forum'] === $base_forum) {
                $forums[] = $x;
            }
        }
    }
    global $M_SORT_KEY;
    $M_SORT_KEY = $order;
    uasort($forums, 'multi_sort');
    $compound_list = '';
    foreach ($forums as $forum) {
        $access = has_category_access($member_id, 'forums', strval($forum['id']));
        $cat_sort_key = '!' . (is_null($forum['f_category_id']) ? '' : strval($forum['f_category_id']));
        if ($access && $skip !== $forum['id'] && $levels !== 0) {
            $cat_bit = '';
            if (!is_null($forum['f_category_id'])) {
                global $CATEGORY_TITLES;
                if (is_null($CATEGORY_TITLES)) {
                    $CATEGORY_TITLES = collapse_2d_complexity('id', 'c_title', $GLOBALS['FORUM_DB']->query_select('f_categories', array('id', 'c_title')));
                }
                $cat_bit = array_key_exists($forum['f_category_id'], $CATEGORY_TITLES) ? $CATEGORY_TITLES[$forum['f_category_id']] : do_lang('NA');
                //if (strlen($pre.$cat_bit)>26) $cat_bit='...';
            }
            if ($field_format) {
                $pre = $tree == '' ? '' : $tree . ' > ';
                $below = ocf_get_forum_tree_secure($member_id, $forum['id'], true, $selected_forum, $pre . $forum['f_name'], $skip, $forum['f_order_sub_alpha'], $use_compound_list, NULL, $do_stats);
                if ($use_compound_list) {
                    list($below, $_compound_list) = $below;
                    $compound_list .= strval($forum['id']) . ',' . $_compound_list;
                }
                $selected = false;
                if (!is_null($selected_forum)) {
                    foreach ($selected_forum as $s) {
                        if (is_integer($s) && $s == $forum['id']) {
                            $selected = true;
                        }
                        if (is_string($s) && $s == $forum['f_name']) {
                            $selected = true;
                        }
                    }
                }
                $line = do_template('OCF_FORUM_LIST_LINE', array('_GUID' => '2fb4bd9ed5c875de6155bef588c877f9', 'PRE' => $pre, 'NAME' => $forum['f_name'], 'CAT_BIT' => $cat_bit));
                if (!array_key_exists($cat_sort_key, $out)) {
                    $out[$cat_sort_key] = '';
                }
                $out[$cat_sort_key] .= '<option value="' . (!$use_compound_list ? strval($forum['id']) : strval($forum['id']) . ',' . $_compound_list) . '"' . ($selected ? ' selected="selected"' : '') . '>' . $line->evaluate() . '</option>';
                //$out.=$below;
                if ($levels !== 0) {
                    $out[$cat_sort_key] .= $below->evaluate();
                }
            } else {
                if ($use_compound_list) {
                    $below = ocf_get_forum_tree_secure($member_id, $forum['id'], true, $selected_forum, $forum['f_name'], $skip, $forum['f_order_sub_alpha'], $use_compound_list, NULL, $do_stats);
                    list($below, $_compound_list) = $below;
                    $compound_list .= strval($forum['id']) . ',' . $_compound_list;
                }
                $element = array('id' => $forum['id'], 'compound_list' => !$use_compound_list ? strval($forum['id']) : strval($forum['id']) . ',' . $_compound_list, 'second_cat' => $cat_bit, 'title' => $forum['f_name'], 'group' => $forum['f_category_id'], 'children' => ocf_get_forum_tree_secure($member_id, $forum['id'], false, $selected_forum, $tree, $skip, false, false, $levels, $do_stats));
                if ($do_stats) {
                    $element['child_count'] = $GLOBALS['FORUM_DB']->query_value('f_forums', 'COUNT(*)', array('f_parent_forum' => $forum['id']));
                }
                if (!array_key_exists($cat_sort_key, $out)) {
                    $out[$cat_sort_key] = array();
                }
                $out[$cat_sort_key][] = $element;
            }
        }
    }
    // Up to now we worked into an array, so we could benefit from how it would auto-sort into the category>forum-position ordering ocPortal uses. Now we need to unzip it
    $real_out = mixed();
    if ($field_format) {
        $real_out = '';
        foreach ($out as $str) {
            $real_out .= $str;
        }
    } else {
        $real_out = array();
        foreach ($out as $arr) {
            $real_out = array_merge($real_out, $arr);
        }
    }
    if ($field_format) {
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($real_out);
        }
        $real_out = make_string_tempcode($real_out);
    }
    if ($use_compound_list) {
        return array($real_out, $compound_list);
    } else {
        return $real_out;
    }
}
Beispiel #11
0
    /**
     * Output an XML-RPC packet (hopefully) to the AJAX in the frontend.
     *
     * @return boolean			Success?
     */
    function output_xml()
    {
        if (count($this->parsed_input) < 1) {
            return false;
        }
        header('Content-Type: text/xml');
        header('HTTP/1.0 200 Ok');
        if (is_object($this->output[STREAM_STDCOMMAND])) {
            $this->output[STREAM_STDCOMMAND] = $this->output[STREAM_STDCOMMAND]->evaluate();
        }
        if (is_object($this->output[STREAM_STDHTML])) {
            $this->output[STREAM_STDHTML] = $this->output[STREAM_STDHTML]->evaluate();
        }
        if (is_object($this->output[STREAM_STDOUT])) {
            $this->output[STREAM_STDOUT] = $this->output[STREAM_STDOUT]->evaluate();
        }
        if (is_object($this->output[STREAM_STDERR])) {
            $this->output[STREAM_STDERR] = $this->output[STREAM_STDERR]->evaluate();
        }
        $output = '<' . '?xml version="1.0" encoding="utf-8" ?' . '>
<response>
	<result>
		<command>' . xmlentities($this->current_input) . '</command>
		<stdcommand>' . $this->output[STREAM_STDCOMMAND] . '</stdcommand>
		<stdhtml><div xmlns="http://www.w3.org/1999/xhtml">' . $this->output[STREAM_STDHTML] . '</div></stdhtml>
		<stdout>' . xmlentities($this->output[STREAM_STDOUT]) . '</stdout>
		<stderr>' . xmlentities($this->output[STREAM_STDERR]) . '</stderr>
		<stdnotifications>' . get_queued_messages() . '</stdnotifications>
	</result>
</response>';
        if ($GLOBALS['XSS_DETECT']) {
            if (ocp_is_escaped($this->output[STREAM_STDHTML])) {
                ocp_mark_as_escaped($output);
            }
        }
        echo $output;
        set_value('last_occle_command', strval(time()));
        return true;
    }
Beispiel #12
0
 /**
  * This function is a very basic query executor. It shouldn't usually be used by you, as there are abstracted versions available.
  *
  * @param  string			The complete SQL query
  * @param  array			A DB connection
  * @param  ?integer		The maximum number of rows to affect (NULL: no limit)
  * @param  ?integer		The start row to affect (NULL: no specification)
  * @param  boolean		Whether to output an error on failure
  * @param  boolean		Whether to get the autoincrement ID created for an insert query
  * @return ?mixed			The results (NULL: no results), or the insert ID
  */
 function db_query($query, $db, $max = NULL, $start = NULL, $fail_ok = false, $get_insert_id = false)
 {
     if (!is_null($max)) {
         if (is_null($start)) {
             $max += $start;
         }
         if (strtoupper(substr($query, 0, 7)) == 'SELECT ') {
             $query .= ' FETCH FIRST ' . strval($max + $start) . ' ROWS ONLY';
         }
     }
     $results = @odbc_exec($db, $query);
     if ($results === false && !$fail_ok) {
         $err = odbc_errormsg($db);
         if (function_exists('ocp_mark_as_escaped')) {
             ocp_mark_as_escaped($err);
         }
         if (!running_script('upgrader') && get_page_name() != 'admin_import') {
             if (!function_exists('do_lang') || is_null(do_lang('QUERY_FAILED', NULL, NULL, NULL, NULL, false))) {
                 fatal_exit(htmlentities('Query failed: ' . $query . ' : ' . $err));
             }
             fatal_exit(do_lang_tempcode('QUERY_FAILED', escape_html($query), $err));
         } else {
             echo htmlentities('Database query failed: ' . $query . ' [') . $err . htmlentities(']' . '<br />' . chr(10));
             return NULL;
         }
     }
     if (strtoupper(substr($query, 0, 7)) == 'SELECT ' && !$results !== false) {
         return $this->db_get_query_rows($results);
     }
     if ($get_insert_id) {
         if (strtoupper(substr($query, 0, 7)) == 'UPDATE ') {
             return NULL;
         }
         $pos = strpos($query, '(');
         $table_name = substr($query, 12, $pos - 13);
         $res2 = odbc_exec($db, 'SELECT MAX(id) FROM ' . $table_name);
         $ar2 = odbc_fetch_row($res2);
         return $ar2[0];
     }
     return NULL;
 }
/**
 * Apply whatever escaping is requested to the given value.
 *
 * @param  array			A list of escaping to do
 * @param  string			The string to apply the escapings to
 * @return string			Output string
 */
function apply_tempcode_escaping_inline($escaped, $value)
{
    global $HTML_ESCAPE_1_STRREP, $HTML_ESCAPE_2;
    foreach (array_reverse($escaped) as $escape) {
        if ($escape == ENTITY_ESCAPED) {
            $value = str_replace($HTML_ESCAPE_1_STRREP, $HTML_ESCAPE_2, $value);
        } elseif ($escape == FORCIBLY_ENTITY_ESCAPED) {
            $value = str_replace($HTML_ESCAPE_1_STRREP, $HTML_ESCAPE_2, $value);
        } elseif ($escape == SQ_ESCAPED) {
            $value = str_replace('&#039;', '\\&#039;', str_replace('\'', '\\\'', str_replace('\\', '\\\\', $value)));
        } elseif ($escape == DQ_ESCAPED) {
            $value = str_replace('&quot;', '\\&quot;', str_replace('"', '\\"', str_replace('\\', '\\\\', $value)));
        } elseif ($escape == NL_ESCAPED) {
            $value = str_replace(chr(13), '', str_replace(chr(10), '', $value));
        } elseif ($escape == NL2_ESCAPED) {
            $value = str_replace(chr(13), '', str_replace(chr(10), '\\n', $value));
        } elseif ($escape == CC_ESCAPED) {
            $value = str_replace('[', '\\[', str_replace('\\', '\\\\', $value));
        } elseif ($escape == UL_ESCAPED) {
            $value = ocp_url_encode($value);
        } elseif ($escape == UL2_ESCAPED) {
            $value = rawurlencode($value);
        } elseif ($escape == JSHTML_ESCAPED) {
            $value = str_replace(']]>', ']]\'+\'>', str_replace('</', '<\\/', $value));
        } elseif ($escape == ID_ESCAPED) {
            $value = fix_id($value);
        } elseif ($escape == CSS_ESCAPED) {
            $value = preg_replace('#[^\\w\\#\\.\\-\\%]#', '_', $value);
        } elseif ($escape == NAUGHTY_ESCAPED) {
            $value = filter_naughty_harsh($value, true);
        }
    }
    if ($GLOBALS['XSS_DETECT'] && $escaped != array()) {
        ocp_mark_as_escaped($value);
    }
    return $value;
}
Beispiel #14
0
 /**
  * Standard modular run function.
  *
  * @return tempcode	The result of execution.
  */
 function run()
 {
     if (get_forum_type() != 'ocf') {
         warn_exit(do_lang_tempcode('NO_OCF'));
     } else {
         ocf_require_all_forum_stuff();
     }
     require_code('ocf_topicview');
     require_css('ocf');
     global $NON_CANONICAL_PARAMS;
     $NON_CANONICAL_PARAMS[] = 'max';
     $NON_CANONICAL_PARAMS[] = 'start';
     $NON_CANONICAL_PARAMS[] = 'threaded';
     $start = get_param_integer('start', 0);
     $default_max = intval(get_option('forum_posts_per_page'));
     $max = get_param_integer('max', $default_max);
     if ($max == 0) {
         $max = $default_max;
     }
     if ($max == 0) {
         $max = 1;
     }
     if ($max > 30 && !has_specific_permission(get_member(), 'remove_page_split')) {
         $max = $default_max;
     }
     $first_unread_id = -1;
     global $NON_CANONICAL_PARAMS;
     foreach (array_keys($_GET) as $key) {
         if (substr($key, 0, 3) == 'kfs') {
             $NON_CANONICAL_PARAMS[] = $key;
         }
     }
     $type = get_param('type', 'misc');
     $id = get_param_integer('id', NULL);
     if (is_guest() && is_null($id)) {
         access_denied('NOT_AS_GUEST');
     }
     if ($type == 'findpost') {
         $post_id = get_param_integer('id');
         $redirect = find_post_id_url($post_id);
         require_code('site2');
         assign_refresh($redirect, 0.0);
         return do_template('REDIRECT_SCREEN', array('_GUID' => '76e6d34c20a4f5284119827e41c7752f', 'URL' => $redirect, 'TITLE' => get_page_title('VIEW_TOPIC'), 'TEXT' => do_lang_tempcode('REDIRECTING')));
     } else {
         if ($type == 'first_unread') {
             $redirect = find_first_unread_url($id);
             require_code('site2');
             assign_refresh($redirect, 0.0);
             return do_template('REDIRECT_SCREEN', array('_GUID' => '12c5d16f60e8c4df03536d9a7a932528', 'URL' => $redirect, 'TITLE' => get_page_title('VIEW_TOPIC'), 'TEXT' => do_lang_tempcode('REDIRECTING')));
         }
     }
     if (!is_null($id)) {
         $GLOBALS['FEED_URL'] = find_script('backend') . '?mode=ocf_topicview&filter=' . strval($id);
     }
     $view_poll_results = get_param_integer('view_poll_results', 0);
     // Mark as read
     if (!is_null($id)) {
         if (!is_guest()) {
             $GLOBALS['FORUM_DB']->query_delete('f_read_logs', array('l_member_id' => get_member(), 'l_topic_id' => $id), '', 1);
             $GLOBALS['FORUM_DB']->query_insert('f_read_logs', array('l_member_id' => get_member(), 'l_topic_id' => $id, 'l_time' => time()), false, true);
             // race condition
         }
         $GLOBALS['FORUM_DB']->query('UPDATE ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_topics SET t_num_views=(t_num_views+1) WHERE id=' . strval((int) $id), 1, NULL, true);
     }
     // Load up topic info
     $topic_info = ocf_read_in_topic($id, $start, $max, $view_poll_results == 1);
     $GLOBALS['META_DATA'] += $topic_info['meta_data'];
     global $SEO_TITLE;
     $SEO_TITLE = do_lang('_VIEW_TOPIC', $topic_info['title']);
     // Render posts according to whether threaded or not
     $threaded = $topic_info['is_threaded'] == 1;
     $may_reply = array_key_exists('may_reply', $topic_info) && ($topic_info['is_open'] || array_key_exists('may_post_closed', $topic_info));
     if (!$threaded) {
         $GLOBALS['META_DATA']['description'] = $topic_info['description'];
         // Poster detail hooks
         $hooks = find_all_hooks('modules', 'topicview');
         $hook_objects = array();
         foreach (array_keys($hooks) as $hook) {
             require_code('hooks/modules/topicview/' . filter_naughty_harsh($hook));
             $object = object_factory('Hook_' . filter_naughty_harsh($hook), true);
             if (is_null($object)) {
                 continue;
             }
             $hook_objects[$hook] = $object;
         }
         // Render non-threaded
         $posts = new ocp_tempcode();
         $replied = false;
         if (is_null($topic_info['forum_id'])) {
             decache('side_ocf_personal_topics', array(get_member()));
             decache('_new_pp', array(get_member()));
         }
         $second_poster = $topic_info['first_poster'];
         foreach ($topic_info['posts'] as $array_id => $_postdetails) {
             if ($array_id == 0) {
                 $description = $topic_info['description'];
             } else {
                 $description = NULL;
             }
             if ($_postdetails['poster'] == get_member()) {
                 $replied = true;
             }
             if ($array_id == 1 && $start == 0 || $array_id == 0 && $start != 0) {
                 $second_poster = $_postdetails['poster'];
             }
             if (array_key_exists('last_edit_time', $_postdetails)) {
                 $last_edited = do_template('OCF_TOPIC_POST_LAST_EDITED', array('_GUID' => '77a28e8bc3cf2ec2211aafdb5ba192bf', 'LAST_EDIT_DATE_RAW' => is_null($_postdetails['last_edit_time']) ? '' : strval($_postdetails['last_edit_time']), 'LAST_EDIT_DATE' => $_postdetails['last_edit_time_string'], 'LAST_EDIT_PROFILE_URL' => $GLOBALS['FORUM_DRIVER']->member_profile_url($_postdetails['last_edit_by'], false, true), 'LAST_EDIT_USERNAME' => $_postdetails['last_edit_by_username']));
             } else {
                 $last_edited = new ocp_tempcode();
             }
             $last_edited_raw = array_key_exists('last_edit_time', $_postdetails) ? is_null($_postdetails['last_edit_time']) ? '' : strval($_postdetails['last_edit_time']) : '0';
             $is_spacer_post = $_postdetails['is_spacer_post'];
             // Post buttons
             $buttons = new ocp_tempcode();
             if (!$is_spacer_post) {
                 $buttons = ocf_render_post_buttons($topic_info, $_postdetails, $may_reply);
             }
             // Avatar
             if (array_key_exists('poster_avatar', $_postdetails) && $_postdetails['poster_avatar'] != '') {
                 $post_avatar = do_template('OCF_TOPIC_POST_AVATAR', array('_GUID' => 'd647ada9c11d56eedc0ff7894d33e83c', 'AVATAR' => $_postdetails['poster_avatar']));
             } else {
                 $post_avatar = new ocp_tempcode();
             }
             // Rank images
             $rank_images = new ocp_tempcode();
             if (!$is_spacer_post) {
                 $posters_groups = $GLOBALS['FORUM_DRIVER']->get_members_groups($_postdetails['poster'], 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($_postdetails['poster'], 'm_primary_group'))) {
                         $rank_images->attach(do_template('OCF_RANK_IMAGE', array('_GUID' => '0ff7855482b901be95591964d4212c44', 'GROUP_NAME' => $group_name, 'USERNAME' => $GLOBALS['FORUM_DRIVER']->get_username($_postdetails['poster']), 'IMG' => $rank_image, 'IS_LEADER' => $group_leader == $_postdetails['poster'])));
                     }
                 }
             }
             // Poster details
             if (!$is_spacer_post) {
                 if (!is_guest($_postdetails['poster'])) {
                     require_code('ocf_members2');
                     $poster_details = ocf_show_member_box($_postdetails, false, $hooks, $hook_objects, false);
                 } else {
                     $custom_fields = new ocp_tempcode();
                     if (array_key_exists('ip_address', $_postdetails)) {
                         $custom_fields->attach(do_template('OCF_TOPIC_POST_CUSTOM_FIELD', array('_GUID' => 'd85be094dff0d039a64120d6f8f381bb', 'NAME' => do_lang_tempcode('IP_ADDRESS'), 'VALUE' => $_postdetails['ip_address'])));
                         $poster_details = do_template('OCF_GUEST_DETAILS', array('_GUID' => 'e43534acaf598008602e8da8f9725f38', 'CUSTOM_FIELDS' => $custom_fields));
                     } else {
                         $poster_details = new ocp_tempcode();
                     }
                 }
             } else {
                 $poster_details = new ocp_tempcode();
             }
             if (!is_guest($_postdetails['poster'])) {
                 $poster = do_template('OCF_POSTER_MEMBER', array('_GUID' => 'dbbed1850b6c01a6c9601d85c6aee43f', 'ONLINE' => member_is_online($_postdetails['poster']), 'ID' => strval($_postdetails['poster']), 'POSTER_DETAILS' => $poster_details, 'PROFILE_URL' => $GLOBALS['FORUM_DRIVER']->member_profile_url($_postdetails['poster'], false, true), 'POSTER_USERNAME' => $_postdetails['poster_username'], 'HIGHLIGHT_NAME' => array_key_exists('poster_highlighted_name', $_postdetails) ? strval($_postdetails['poster_highlighted_name']) : NULL));
             } else {
                 $ip_link = array_key_exists('ip_address', $_postdetails) && has_actual_page_access(get_member(), 'admin_lookup') ? build_url(array('page' => 'admin_lookup', 'param' => $_postdetails['ip_address']), get_module_zone('admin_lookup')) : new ocp_tempcode();
                 $poster = do_template('OCF_POSTER_GUEST', array('_GUID' => '36a8e550222cdac5165ef8f722be3def', 'IP_LINK' => $ip_link, 'POSTER_DETAILS' => $poster_details, 'POSTER_USERNAME' => $_postdetails['poster_username']));
             }
             // Signature
             $signature = new ocp_tempcode();
             if (array_key_exists('signature', $_postdetails) && !$_postdetails['signature']->is_empty()) {
                 $signature = $_postdetails['signature'];
             }
             $post_title = $_postdetails['title'];
             $first_unread = $_postdetails['id'] == $first_unread_id || $first_unread_id < 0 && $array_id == count($topic_info['posts']) - 1 ? do_template('OCF_TOPIC_FIRST_UNREAD') : new ocp_tempcode();
             $unvalidated = $_postdetails['validated'] == 0 ? do_lang_tempcode('UNVALIDATED') : new ocp_tempcode();
             $post_url = $GLOBALS['FORUM_DRIVER']->post_url($_postdetails['id'], is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']), true);
             if (array_key_exists('intended_solely_for', $_postdetails) && $_postdetails['intended_solely_for'] == get_member()) {
                 decache('side_ocf_personal_topics', array(get_member()));
                 decache('_new_pp', array(get_member()));
             }
             $emphasis = ocf_get_post_emphasis($_postdetails);
             require_code('feedback');
             if (!array_key_exists('intended_solely_for', $_postdetails)) {
                 actualise_rating(true, 'post', strval($_postdetails['id']), get_self_url(), $_postdetails['title']);
                 $rating = display_rating(get_self_url(), $_postdetails['title'], 'post', strval($_postdetails['id']), 'RATING_INLINE_DYNAMIC', $_postdetails['poster']);
             } else {
                 $rating = new ocp_tempcode();
             }
             $rendered_post = do_template('OCF_TOPIC_POST', array('_GUID' => 'sacd09wekfofpw2f', 'ID' => $is_spacer_post ? '' : strval($_postdetails['id']), 'TOPIC_FIRST_POST_ID' => is_null($topic_info['first_post_id']) ? '' : strval($topic_info['first_post_id']), 'TOPIC_FIRST_POSTER' => is_null($topic_info['first_poster']) ? '' : strval($topic_info['first_poster']), 'POST_ID' => $is_spacer_post ? '' : (get_value('seq_post_ids') === '1' ? strval($start + $array_id + 1) : strval($_postdetails['id'])), 'URL' => $post_url, 'CLASS' => $_postdetails['is_emphasised'] ? 'ocf_post_emphasis' : (array_key_exists('intended_solely_for', $_postdetails) ? 'ocf_post_personal' : ''), 'EMPHASIS' => $emphasis, 'FIRST_UNREAD' => $first_unread, 'POSTER_TITLE' => $is_spacer_post ? '' : $_postdetails['poster_title'], 'POST_TITLE' => $post_title, 'POST_DATE_RAW' => strval($_postdetails['time']), 'POST_DATE' => $_postdetails['time_string'], 'POST' => $_postdetails['post'], 'TOPIC_ID' => is_null($id) ? '' : strval($id), 'LAST_EDITED_RAW' => $last_edited_raw, 'LAST_EDITED' => $last_edited, 'POSTER_ID' => strval($_postdetails['poster']), 'POSTER' => $is_spacer_post ? '' : $poster, 'POSTER_DETAILS' => $poster_details, 'POST_AVATAR' => $post_avatar, 'RANK_IMAGES' => $rank_images, 'BUTTONS' => $buttons, 'SIGNATURE' => $signature, 'UNVALIDATED' => $unvalidated, 'DESCRIPTION' => $description, 'RATING' => $rating));
             $posts->attach($rendered_post);
         }
         $serialized_options = mixed();
         $hash = mixed();
     } else {
         require_code('topics');
         $threaded_topic_ob = new OCP_Topic();
         // Load some settings into the renderer
         $threaded_topic_ob->first_post_id = $topic_info['first_post_id'];
         $threaded_topic_ob->topic_description = $topic_info['description'];
         $threaded_topic_ob->topic_description_link = $topic_info['description_link'];
         $threaded_topic_ob->topic_title = $topic_info['title'];
         $threaded_topic_ob->topic_info = $topic_info;
         // Other settings we need
         $max_thread_depth = intval(get_option('max_thread_depth'));
         $num_to_show_limit = get_param_integer('max_comments', intval(get_option('comments_to_show_in_thread')));
         // Load posts
         $threaded_topic_ob->load_from_topic($id, $num_to_show_limit, $start, false, NULL, true);
         $threaded_topic_ob->is_threaded = true;
         // Render posts
         list($posts, $serialized_options, $hash) = $threaded_topic_ob->render_posts($num_to_show_limit, $max_thread_depth, $may_reply, $topic_info['first_poster'], array(), $topic_info['forum_id'], NULL, false);
         $GLOBALS['META_DATA']['description'] = $threaded_topic_ob->topic_description;
         // Get other gathered details
         $replied = $threaded_topic_ob->replied;
         if (!is_null($threaded_topic_ob->topic_title)) {
             // Updated topic title
             $topic_info['title'] = $threaded_topic_ob->topic_title;
         }
         $topic_info['max_rows'] = $threaded_topic_ob->total_posts;
         $second_poster = $GLOBALS['FORUM_DRIVER']->get_guest_id();
         // No definitive post orders
     }
     // Buttons for topic as whole
     $button_array = array();
     if (!is_null($id)) {
         if (get_value('no_threaded_buttons') !== '1') {
             if ($threaded) {
                 $view_as_linear_url = get_self_url(false, false, array('threaded' => 0));
                 $button_array[] = array('immediate' => true, 'title' => do_lang_tempcode('VIEW_AS_LINEAR'), 'url' => $view_as_linear_url, 'img' => 'linear');
             } else {
                 $view_as_threaded_url = get_self_url(false, false, array('threaded' => 1));
                 $button_array[] = array('immediate' => true, 'title' => do_lang_tempcode('VIEW_AS_THREADED'), 'url' => $view_as_threaded_url, 'img' => 'threaded');
             }
         }
         if (!is_guest()) {
             $too_old = $topic_info['last_time'] < time() - 60 * 60 * 24 * intval(get_option('post_history_days'));
             if (get_value('disable_mark_topic_unread') !== '1' && !$too_old) {
                 $map = array('page' => 'topics', 'type' => 'mark_unread_topic', 'id' => $id);
                 $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
                 if ($test != -1 && $test != 0) {
                     $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
                 }
                 $test = get_param_integer('threaded', -1);
                 if ($test != -1) {
                     $map['threaded'] = $test;
                 }
                 $mark_unread_url = build_url($map, get_module_zone('topics'));
                 $button_array[] = array('immediate' => true, 'title' => do_lang_tempcode('MARK_UNREAD'), 'url' => $mark_unread_url, 'img' => 'mark_unread');
             }
         }
         if ($may_reply && is_null(get_bot_type())) {
             $reply_prevented = false;
             // "Staff-only" reply for support tickets
             if ($GLOBALS['FORUM_DRIVER']->is_staff(get_member()) && addon_installed('tickets')) {
                 require_code('tickets');
                 if (is_ticket_forum($topic_info['forum_id'])) {
                     if (is_guest($second_poster)) {
                         $reply_prevented = true;
                     }
                     require_lang('tickets');
                     $map = array('page' => 'topics', 'type' => 'new_post', 'id' => $id, 'intended_solely_for' => $GLOBALS['FORUM_DRIVER']->get_guest_id());
                     $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
                     if ($test != -1 && $test != 0) {
                         $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
                     }
                     $test = get_param_integer('threaded', -1);
                     if ($test != -1) {
                         $map['threaded'] = $test;
                     }
                     $new_post_url = build_url($map, get_module_zone('topics'));
                     $button_array[] = array('immediate' => false, 'rel' => 'add', 'title' => do_lang_tempcode('TICKET_STAFF_ONLY_REPLY'), 'url' => $new_post_url, 'img' => 'staff_only_reply');
                 }
             }
             if (!$reply_prevented) {
                 if ($topic_info['is_threaded'] == 0) {
                     $map = array('page' => 'topics', 'type' => 'new_post', 'id' => $id);
                     $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
                     if ($test != -1 && $test != 0) {
                         $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
                     }
                     $test = get_param_integer('threaded', -1);
                     if ($test != -1) {
                         $map['threaded'] = $test;
                     }
                     $new_post_url = build_url($map, get_module_zone('topics'));
                     $button_array[] = array('immediate' => false, 'rel' => 'add', 'title' => do_lang_tempcode($topic_info['is_open'] ? 'REPLY' : 'CLOSED'), 'url' => $new_post_url, 'img' => $topic_info['is_open'] ? 'reply' : 'closed');
                 }
             } else {
                 unset($topic_info['may_use_quick_reply']);
             }
         } elseif ((is_null($topic_info['forum_id']) || has_specific_permission(get_member(), 'submit_lowrange_content', 'topics', array('forums', $topic_info['forum_id']))) && $topic_info['last_poster'] == get_member() && !is_guest() && ocf_may_edit_post_by(get_member(), $topic_info['forum_id'])) {
             $map = array('page' => 'topics', 'type' => 'edit_post', 'id' => $topic_info['last_post_id']);
             $test = get_param_integer('kfs' . strval($topic_info['forum_id']), -1);
             if ($test != -1 && $test != 0) {
                 $map['kfs' . strval($topic_info['forum_id'])] = $test;
             }
             $test = get_param_integer('threaded', -1);
             if ($test != -1) {
                 $map['threaded'] = $test;
             }
             $new_post_url = build_url($map, get_module_zone('topics'));
             $button_array[] = array('immediate' => false, 'rel' => 'edit', 'title' => do_lang_tempcode('LAST_POST'), 'url' => $new_post_url, 'img' => 'amend');
         }
         if (!is_null($topic_info['forum_id'])) {
             if (get_value('disable_add_topic_btn_in_topic') !== '1') {
                 if (ocf_may_post_topic($topic_info['forum_id'], get_member())) {
                     $new_topic_url = build_url(array('page' => 'topics', 'type' => 'new_topic', 'id' => $topic_info['forum_id']), get_module_zone('topics'));
                     $button_array[] = array('immediate' => false, 'rel' => 'add', 'title' => do_lang_tempcode('ADD_TOPIC'), 'url' => $new_topic_url, 'img' => 'new_topic');
                 }
             }
         } else {
             $invite_url = build_url(array('page' => 'topics', 'type' => 'invite_member', 'id' => $id), get_module_zone('topics'));
             $button_array[] = array('immediate' => false, 'title' => do_lang_tempcode('INVITE_MEMBER_TO_PT'), 'url' => $invite_url, 'img' => 'invite_member');
         }
     }
     $buttons = ocf_screen_button_wrap($button_array);
     // Poll
     if (array_key_exists('poll', $topic_info)) {
         $_poll = $topic_info['poll'];
         $voted_already = $_poll['voted_already'];
         $poll_results = array_key_exists(0, $_poll['answers']) && array_key_exists('num_votes', $_poll['answers'][0]);
         $answers = new ocp_tempcode();
         $real_button = false;
         if ($_poll['is_open']) {
             if ($poll_results) {
                 $button = new ocp_tempcode();
             } elseif ($_poll['requires_reply'] && !$replied) {
                 $button = do_lang_tempcode('POLL_REQUIRES_REPLY');
             } else {
                 if (!has_specific_permission(get_member(), 'vote_in_polls') || is_guest()) {
                     $button = do_lang_tempcode('VOTE_DENIED');
                 } else {
                     if (!is_null($voted_already)) {
                         $button = do_lang_tempcode('NOVOTE');
                     } else {
                         require_lang('polls');
                         $map = array('page' => 'topicview', 'id' => $id, 'view_poll_results' => 1, 'start' => $start == 0 ? NULL : $start, 'max' => $max == $default_max ? NULL : $max);
                         $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
                         if ($test != -1 && $test != 0) {
                             $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
                         }
                         $test = get_param_integer('threaded', -1);
                         if ($test != -1) {
                             $map['threaded'] = $test;
                         }
                         $results_url = build_url($map, get_module_zone('topics'));
                         $button = do_template('OCF_TOPIC_POLL_BUTTON', array('_GUID' => '94b932fd01028df8f67bb5864d9235f9', 'RESULTS_URL' => $results_url));
                         $real_button = true;
                     }
                 }
             }
         } else {
             $button = do_lang_tempcode('TOPIC_POLL_CLOSED');
         }
         foreach ($_poll['answers'] as $answer) {
             if ($poll_results && ($_poll['requires_reply'] == 0 || $replied)) {
                 $num_votes = $answer['num_votes'];
                 $total_votes = $_poll['total_votes'];
                 if ($total_votes != 0) {
                     $width = intval(round(70.0 * floatval($num_votes) / floatval($total_votes)));
                 } else {
                     $width = 0;
                 }
                 $answer_tpl = do_template('OCF_TOPIC_POLL_ANSWER_RESULTS', array('_GUID' => 'b32f4c526e147abf20ca0d668e40d515', 'ID' => strval($_poll['id']), 'NUM_VOTES' => integer_format($num_votes), 'WIDTH' => strval($width), 'ANSWER' => $answer['answer'], 'I' => strval($answer['id'])));
             } else {
                 $answer_tpl = do_template('OCF_TOPIC_POLL_ANSWER' . ($_poll['maximum_selections'] == 1 ? '_RADIO' : ''), array('REAL_BUTTON' => $real_button, 'ID' => strval($_poll['id']), 'ANSWER' => $answer['answer'], 'I' => strval($answer['id'])));
             }
             $answers->attach($answer_tpl);
         }
         $map = array('page' => 'topics', 'type' => 'vote_poll', 'id' => $id, 'start' => $start == 0 ? NULL : $start, 'max' => $max == $default_max ? NULL : $max);
         $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
         if ($test != -1 && $test != 0) {
             $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
         }
         $test = get_param_integer('threaded', -1);
         if ($test != -1) {
             $map['threaded'] = $test;
         }
         $vote_url = build_url($map, get_module_zone('topics'));
         if ($_poll['is_private']) {
             $private = paragraph(do_lang_tempcode('TOPIC_POLL_IS_PRIVATE'), 'dfgsdgdsgs');
         } else {
             $private = new ocp_tempcode();
         }
         if ($_poll['maximum_selections'] > 1) {
             $num_choices = paragraph($_poll['minimum_selections'] == $_poll['maximum_selections'] ? do_lang_tempcode('POLL_NOT_ENOUGH_ERROR_2', integer_format($_poll['minimum_selections'])) : do_lang_tempcode('POLL_NOT_ENOUGH_ERROR', integer_format($_poll['minimum_selections']), integer_format($_poll['maximum_selections'])), 'dsfsdfsdfs');
         } else {
             $num_choices = new ocp_tempcode();
         }
         $poll = do_template('OCF_TOPIC_POLL' . ($poll_results ? '_VIEW_RESULTS' : ''), array('ID' => strval($_poll['id']), 'NUM_CHOICES' => $num_choices, 'PRIVATE' => $private, 'QUESTION' => $_poll['question'], 'ANSWERS' => $answers, 'REAL_BUTTON' => $real_button, 'BUTTON' => $button, 'VOTE_URL' => $vote_url, 'MINIMUM_SELECTIONS' => integer_format($_poll['minimum_selections']), 'MAXIMUM_SELECTIONS' => integer_format($_poll['maximum_selections'])));
     } else {
         $poll = new ocp_tempcode();
     }
     // Forum nav tree
     if (!is_null($topic_info['forum_id'])) {
         $tree = ocf_forum_breadcrumbs($topic_info['forum_id'], NULL, NULL, false);
     } else {
         $tree = new ocp_tempcode();
         $tree->attach(hyperlink(build_url(array('page' => 'members'), get_module_zone('members')), do_lang_tempcode('MEMBERS'), false, false, do_lang_tempcode('GO_BACKWARDS_TO', do_lang_tempcode('MEMBERS')), NULL, NULL, 'up'));
         $tree->attach(do_template('BREADCRUMB_ESCAPED'));
         if (has_specific_permission(get_member(), 'view_other_pt')) {
             $of_member = $topic_info['pt_from'] == get_member() ? $topic_info['pt_from'] : $topic_info['pt_to'];
         } else {
             $of_member = get_member();
         }
         $of_username = $GLOBALS['FORUM_DRIVER']->get_username($of_member);
         if (is_null($of_username)) {
             $of_username = do_lang('UNKNOWN');
         }
         $personal_topic_url = build_url(array('page' => 'members', 'type' => 'view', 'id' => $of_member), get_module_zone('members'), NULL, true, false, false, 'tab__pts');
         $tree->attach(hyperlink($personal_topic_url, do_lang_tempcode('MEMBER_PROFILE', escape_html($of_username)), false, false, do_lang_tempcode('GO_BACKWARDS_TO', do_lang_tempcode('MEMBERS')), NULL, NULL, 'up'));
     }
     // Quick reply
     if (array_key_exists('may_use_quick_reply', $topic_info) && $may_reply && !is_null($id)) {
         $map = array('page' => 'topics', 'type' => '_add_reply', 'topic_id' => $id);
         $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
         if ($test != -1 && $test != 0) {
             $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
         }
         $test = get_param_integer('threaded', -1);
         if ($test != -1) {
             $map['threaded'] = $test;
         }
         $_post_url = build_url($map, get_module_zone('topics'));
         $post_url = $_post_url->evaluate();
         $map = array('page' => 'topics', 'type' => 'new_post', 'id' => $id);
         if ($test != -1 && $test != 0) {
             $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
         }
         $more_url = build_url($map, get_module_zone('topics'));
         $_postdetails = array_key_exists('first_post', $topic_info) ? get_translated_tempcode($topic_info['first_post'], $GLOBALS['FORUM_DB']) : new ocp_tempcode();
         $first_post = $_postdetails;
         $first_post_url = $GLOBALS['FORUM_DRIVER']->post_url($topic_info['first_post_id'], is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']), true);
         $display = 'block';
         $expand_type = 'contract';
         if ($topic_info['max_rows'] > $start + $max) {
             $display = 'none';
             $expand_type = 'expand';
         }
         $em = $GLOBALS['FORUM_DRIVER']->get_emoticon_chooser();
         require_javascript('javascript_editing');
         require_javascript('javascript_validation');
         if (addon_installed('captcha')) {
             require_code('captcha');
             $use_captcha = use_captcha();
             if ($use_captcha) {
                 generate_captcha();
             }
         } else {
             $use_captcha = false;
         }
         $post_warning = '';
         if ($topic_info['is_really_threaded'] == 1) {
             $post_warning = do_lang('THREADED_REPLY_NOTICE', $post_warning);
         }
         $quick_reply = do_template('COMMENTS_POSTING_FORM', array('_GUID' => '4c532620f3eb68d9cc820b18265792d7', 'JOIN_BITS' => '', 'USE_CAPTCHA' => $use_captcha, 'GET_EMAIL' => false, 'EMAIL_OPTIONAL' => true, 'GET_TITLE' => false, 'POST_WARNING' => $post_warning, 'COMMENT_TEXT' => '', 'EM' => $em, 'EXPAND_TYPE' => $expand_type, 'DISPLAY' => $display, 'FIRST_POST_URL' => $first_post_url, 'FIRST_POST' => $first_post, 'MORE_URL' => $more_url, 'COMMENT_URL' => $post_url, 'TITLE' => do_lang_tempcode('QUICK_REPLY'), 'SUBMIT_NAME' => do_lang_tempcode('MAKE_POST')));
     } else {
         $quick_reply = new ocp_tempcode();
     }
     $action_url = build_url(array('page' => 'topics', 'id' => $id), get_module_zone('topics'));
     if (!is_null($id)) {
         // Moderation options
         $moderator_actions = '';
         if (is_null($topic_info['forum_id'])) {
             $moderator_actions .= '<option value="categorise_pts">' . do_lang('_CATEGORISE_PTS') . '</option>';
         }
         if (array_key_exists('may_multi_moderate', $topic_info) && array_key_exists('forum_id', $topic_info)) {
             $multi_moderations = ocf_list_multi_moderations($topic_info['forum_id']);
             if (count($multi_moderations) != 0) {
                 $moderator_actions .= '<optgroup label="' . do_lang('MULTI_MODERATIONS') . '">';
                 foreach ($multi_moderations as $mm_id => $mm_name) {
                     $moderator_actions .= '<option value="mm_' . strval($mm_id) . '">' . $mm_name . '</option>';
                 }
                 $moderator_actions .= '</optgroup>';
             }
         }
         if (array_key_exists('may_move_topic', $topic_info)) {
             $moderator_actions .= '<option value="move_topic">' . do_lang('MOVE_TOPIC') . '</option>';
         }
         if (array_key_exists('may_edit_topic', $topic_info)) {
             $moderator_actions .= '<option value="edit_topic">' . do_lang('EDIT_TOPIC') . '</option>';
         }
         if (array_key_exists('may_delete_topic', $topic_info)) {
             $moderator_actions .= '<option value="delete_topic">' . do_lang('DELETE_TOPIC') . '</option>';
         }
         if (array_key_exists('may_pin_topic', $topic_info)) {
             $moderator_actions .= '<option value="pin_topic">' . do_lang('PIN_TOPIC') . '</option>';
         }
         if (array_key_exists('may_unpin_topic', $topic_info)) {
             $moderator_actions .= '<option value="unpin_topic">' . do_lang('UNPIN_TOPIC') . '</option>';
         }
         if (array_key_exists('may_sink_topic', $topic_info)) {
             $moderator_actions .= '<option value="sink_topic">' . do_lang('SINK_TOPIC') . '</option>';
         }
         if (array_key_exists('may_unsink_topic', $topic_info)) {
             $moderator_actions .= '<option value="unsink_topic">' . do_lang('UNSINK_TOPIC') . '</option>';
         }
         if (array_key_exists('may_cascade_topic', $topic_info)) {
             $moderator_actions .= '<option value="cascade_topic">' . do_lang('CASCADE_TOPIC') . '</option>';
         }
         if (array_key_exists('may_uncascade_topic', $topic_info)) {
             $moderator_actions .= '<option value="uncascade_topic">' . do_lang('UNCASCADE_TOPIC') . '</option>';
         }
         if (array_key_exists('may_open_topic', $topic_info)) {
             $moderator_actions .= '<option value="open_topic">' . do_lang('OPEN_TOPIC') . '</option>';
         }
         if (array_key_exists('may_close_topic', $topic_info)) {
             $moderator_actions .= '<option value="close_topic">' . do_lang('CLOSE_TOPIC') . '</option>';
         }
         if (array_key_exists('may_edit_poll', $topic_info)) {
             $moderator_actions .= '<option value="edit_poll">' . do_lang('EDIT_TOPIC_POLL') . '</option>';
         }
         if (array_key_exists('may_delete_poll', $topic_info)) {
             $moderator_actions .= '<option value="delete_poll">' . do_lang('DELETE_TOPIC_POLL') . '</option>';
         }
         if (array_key_exists('may_attach_poll', $topic_info)) {
             $moderator_actions .= '<option value="add_poll">' . do_lang('ADD_TOPIC_POLL') . '</option>';
         }
         if (has_specific_permission(get_member(), 'view_content_history') && $GLOBALS['FORUM_DB']->query_value('f_post_history', 'COUNT(*)', array('h_topic_id' => $id)) != 0) {
             $moderator_actions .= '<option value="topic_history">' . do_lang('POST_HISTORY') . '</option>';
         }
         if (array_key_exists('may_make_personal', $topic_info) && !is_null($topic_info['forum_id'])) {
             $moderator_actions .= '<option value="make_personal">' . do_lang('MAKE_PERSONAL') . '</option>';
         }
         if ($GLOBALS['XSS_DETECT']) {
             ocp_mark_as_escaped($moderator_actions);
         }
         // Marked post actions
         $map = array('page' => 'topics', 'id' => $id);
         $test = get_param_integer('kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id'])), -1);
         if ($test != -1 && $test != 0) {
             $map['kfs' . (is_null($topic_info['forum_id']) ? '' : strval($topic_info['forum_id']))] = $test;
         }
         $test = get_param_integer('threaded', -1);
         if ($test != -1) {
             $map['threaded'] = $test;
         }
         $action_url = build_url($map, get_module_zone('topics'), NULL, false, true);
         $marked_post_actions = '';
         if (array_key_exists('may_move_posts', $topic_info)) {
             $marked_post_actions .= '<option value="move_posts_a">' . do_lang('MERGE_POSTS') . '</option>';
             $marked_post_actions .= '<option value="move_posts_b">' . do_lang('SPLIT_POSTS') . '</option>';
         }
         if (array_key_exists('may_delete_posts', $topic_info)) {
             $marked_post_actions .= '<option value="delete_posts">' . do_lang('DELETE_POSTS') . '</option>';
         }
         if (array_key_exists('may_validate_posts', $topic_info)) {
             $marked_post_actions .= '<option value="validate_posts">' . do_lang('VALIDATE_POSTS') . '</option>';
         }
         if (get_value('disable_multi_quote') !== '1') {
             if ($may_reply) {
                 $marked_post_actions .= '<option value="new_post">' . do_lang('QUOTE_POSTS') . '</option>';
             }
         }
         if ($GLOBALS['XSS_DETECT']) {
             ocp_mark_as_escaped($marked_post_actions);
         }
     } else {
         $moderator_actions = '';
         $marked_post_actions = '';
     }
     $max_rows = $topic_info['max_rows'];
     if ($max_rows > $max && !$threaded) {
         require_code('templates_results_browser');
         $results_browser = results_browser(do_lang_tempcode('FORUM_POSTS'), $id, $start, 'start', $max, 'max', $max_rows, NULL, 'misc', true, false, 7, array(10, 20, 30));
     } else {
         $results_browser = new ocp_tempcode();
     }
     // Members viewing this topic
     $members = is_null($id) ? array() : get_members_viewing('topicview', '', strval($id), true);
     $num_guests = 0;
     $num_members = 0;
     if (is_null($members)) {
         $members_viewing = new ocp_tempcode();
     } else {
         $members_viewing = new ocp_tempcode();
         foreach ($members as $member_id => $at_details) {
             $username = $at_details['mt_cache_username'];
             if (is_guest($member_id)) {
                 $num_guests++;
             } else {
                 $num_members++;
                 $profile_url = $GLOBALS['FORUM_DRIVER']->member_profile_url($member_id, false, true);
                 $map = array('PROFILE_URL' => $profile_url, 'USERNAME' => $username);
                 if (has_specific_permission(get_member(), 'show_user_browsing') || in_array($at_details['the_page'], array('topics', 'topicview')) && $at_details['the_id'] == strval($id)) {
                     $map['AT'] = escape_html($at_details['the_title']);
                 }
                 $map['COLOUR'] = get_group_colour(ocf_get_member_primary_group($member_id));
                 $members_viewing->attach(do_template('OCF_USER_MEMBER', $map));
             }
         }
         if ($members_viewing->is_empty()) {
             $members_viewing = do_lang_tempcode('NONE_EM');
         }
     }
     if (!is_null($id)) {
         breadcrumb_add_segment($tree, do_lang_tempcode(is_null($topic_info['forum_id']) ? 'VIEW_PERSONAL_TOPIC' : 'VIEW_TOPIC'));
     }
     if (is_null($id)) {
         $root_forum_name = $GLOBALS['FORUM_DB']->query_value('f_forums', 'f_name', array('id' => db_get_first_id()));
         $tree = hyperlink(build_url(array('page' => 'forumview', 'id' => db_get_first_id()), get_module_zone('forumview')), escape_html($root_forum_name), false, false, do_lang('GO_BACKWARDS_TO'));
         breadcrumb_add_segment($tree, do_lang('INLINE_PERSONAL_POSTS'));
     }
     if ($topic_info['validated'] == 0) {
         $warning_details = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode(get_param_integer('redirected', 0) == 1 ? 'UNVALIDATED_TEXT_NON_DIRECT' : 'UNVALIDATED_TEXT')));
     } else {
         $warning_details = new ocp_tempcode();
     }
     $topic_tpl = do_template('OCF_TOPIC_WRAP', array('_GUID' => 'bb201d5d59559e5e2bd60e7cf2e6f7e9', 'SERIALIZED_OPTIONS' => $serialized_options, 'HASH' => $hash, 'ID' => strval($id), 'TITLE' => $topic_info['title'], 'MAY_DOUBLE_POST' => has_specific_permission(get_member(), 'double_post'), 'LAST_POSTER' => array_key_exists('last_poster', $topic_info) ? is_null($topic_info['last_poster']) ? '' : strval($topic_info['last_poster']) : '', 'WARNING_DETAILS' => $warning_details, 'MAX' => strval($max), 'MAY_CHANGE_MAX' => array_key_exists('may_change_max', $topic_info), 'ACTION_URL' => $action_url, 'NUM_GUESTS' => integer_format($num_guests), 'NUM_MEMBERS' => integer_format($num_members), 'MEMBERS_VIEWING' => $members_viewing, 'RESULTS_BROWSER' => $results_browser, 'MODERATOR_ACTIONS' => $moderator_actions, 'MARKED_POST_ACTIONS' => $marked_post_actions, 'QUICK_REPLY' => $quick_reply, 'TREE' => $tree, 'POLL' => $poll, 'SCREEN_BUTTONS' => $buttons, 'POSTS' => $posts, 'THREADED' => $threaded));
     if (is_null($id)) {
         $title = get_page_title('INLINE_PERSONAL_POSTS');
     } else {
         if (is_null($topic_info['forum_id'])) {
             $title = get_page_title(do_lang_tempcode('NAMED_PERSONAL_TOPIC', escape_html($topic_info['title'])), false, NULL, do_lang_tempcode('READING_PERSONAL_TOPIC'));
         } else {
             if (addon_installed('awards')) {
                 require_code('awards');
                 $awards = find_awards_for('topic', strval($id));
             } else {
                 $awards = array();
             }
             $title = get_page_title(do_lang_tempcode('NAMED_TOPIC', escape_html($topic_info['title'])), false, NULL, NULL, $awards);
         }
     }
     return ocf_wrapper($title, $topic_tpl, true, false, $topic_info['forum_id']);
 }
/**
 * Compile a template into a list of appendable outputs, for the closure-style Tempcode implementation.
 *
 * @param  string			The template file contents
 * @param  ID_TEXT		The name of the template
 * @param  ID_TEXT		The name of the theme
 * @param  ID_TEXT		The language it is for
 * @param  boolean		Whether to tolerate errors
 * @return array			A pair: array Compiled result structure, array preprocessable bits (special stuff needing attention that is referenced within the template)
 */
function compile_template($data, $template_name, $theme, $lang, $tolerate_errors = false)
{
    if (strpos($data, '{$,Parser hint: pure}') !== false) {
        return array(array('"' . php_addslashes(preg_replace('#\\{\\$,.*\\}#U', '/*no minify*/', $data)) . '"'), array());
    }
    $data = preg_replace('#<\\?php(.*)\\?' . '>#sU', '{+START,PHP}${1}{+END}', $data);
    $compilable_symbols = array('"ADDON_INSTALLED"', '"COPYRIGHT"', '"SITE_NAME"', '"BRAND_BASE_URL"', '"BRAND_NAME"', '"IMG_WIDTH"', '"IMG_HEIGHT"', '"LANG"', '"THEME"', '"VALUE_OPTION"', '"CONFIG_OPTION"');
    if (function_exists('get_option') && get_option('enable_https', true) != '1') {
        $compilable_symbols[] = '"BASE_URL"';
    }
    global $SITE_INFO;
    if (isset($SITE_INFO['no_keep_params']) && $SITE_INFO['no_keep_params'] == '1') {
        $compilable_symbols[] = '"PAGE_LINK"';
        $compilable_symbols[] = '"FIND_SCRIPT"';
    }
    require_code('lang');
    require_code('urls');
    $cl = fallback_lang();
    $bits = array_values(preg_split('#(?<!\\\\)(\\{(?=[\\dA-Z\\$\\+\\!\\_]+[\\.`%\\*=\\;\\#\\-~\\^\\|\'&/@]*))|((?<!\\\\)\\,)|((?<!\\\\)\\})#', $data, -1, PREG_SPLIT_DELIM_CAPTURE));
    // One error mail showed on a server it had weird indexes, somehow. Hence the array_values call to reindex it
    $count = count($bits);
    $stack = array();
    $current_level_mode = PARSE_NO_MANS_LAND;
    $current_level_data = array();
    $current_level_params = array();
    $preprocessable_bits = array();
    for ($i = 0; $i < $count; $i++) {
        $next_token = $bits[$i];
        if ($next_token == '') {
            continue;
        }
        if ($i != $count - 1 && $next_token == '{' && preg_match('#^[\\dA-Z\\$\\+\\!\\_]#', $bits[$i + 1]) == 0) {
            $current_level_data[] = '"{}"';
            continue;
        }
        switch ($next_token) {
            case '{':
                // Open a new level
                $stack[] = array($current_level_mode, $current_level_data, $current_level_params, NULL, NULL, NULL);
                ++$i;
                $next_token = isset($bits[$i]) ? $bits[$i] : NULL;
                if (is_null($next_token)) {
                    if ($tolerate_errors) {
                        continue;
                    }
                    warn_exit(do_lang_tempcode('ABRUPTED_DIRECTIVE_OR_BRACE', escape_html($template_name), integer_format(1 + substr_count(substr($data, 0, _length_so_far($bits, $i)), chr(10)))));
                }
                $current_level_data = array();
                switch (substr($next_token, 0, 1)) {
                    case '$':
                        $current_level_mode = PARSE_SYMBOL;
                        $current_level_data[] = '"' . php_addslashes(substr($next_token, 1)) . '"';
                        break;
                    case '+':
                        $current_level_mode = PARSE_DIRECTIVE;
                        $current_level_data[] = '"' . php_addslashes(substr($next_token, 1)) . '"';
                        break;
                    case '!':
                        $current_level_mode = PARSE_LANGUAGE_REFERENCE;
                        $current_level_data[] = '"' . php_addslashes(substr($next_token, 1)) . '"';
                        break;
                    default:
                        $current_level_mode = PARSE_PARAMETER;
                        $current_level_data[] = '"' . php_addslashes($next_token) . '"';
                        break;
                }
                $current_level_params = array();
                break;
            case '}':
                if (count($stack) == 0 || $current_level_mode == PARSE_DIRECTIVE_INNER) {
                    $literal = php_addslashes($next_token);
                    if ($GLOBALS['XSS_DETECT']) {
                        ocp_mark_as_escaped($literal);
                    }
                    $current_level_data[] = '"' . $literal . '"';
                    break;
                }
                $opener_params = array_merge($current_level_params, array($current_level_data));
                $__first_param = array_shift($opener_params);
                $_first_param = implode('.', $__first_param);
                if ($bits[$i - 1] == '') {
                    $current_level_data[] = '""';
                }
                // Return to the previous level
                $past_level_data = $current_level_data;
                $past_level_params = $current_level_params;
                $past_level_mode = $current_level_mode;
                if (count($stack) == 0) {
                    if (!$tolerate_errors) {
                        warn_exit(do_lang_tempcode('TEMPCODE_TOO_MANY_CLOSES', escape_html($template_name), integer_format(1 + _length_so_far($bits, $i))));
                    }
                } else {
                    list($current_level_mode, $current_level_data, $current_level_params, , , ) = array_pop($stack);
                }
                // Handle the level we just closed
                if (function_exists('str_split')) {
                    $_escaped = str_split(preg_replace('#[^:\\.`%\\*=\\;\\#\\-~\\^\\|\'&/@]:?#', '', $_first_param));
                    // :? is so that the ":" in lang strings does not get considered an escape
                } else {
                    $temp = preg_replace('#[^:\\.`%\\*=\\;\\#\\-~\\^\\|\'&/@]:?#', '', $_first_param);
                    $_escaped = array();
                    for ($j = 0; $j < strlen($temp); $j++) {
                        $_escaped[] = $temp[$j];
                    }
                }
                $escaped = array();
                foreach ($_escaped as $e) {
                    switch ($e) {
                        case '`':
                            $escaped[] = NULL_ESCAPED;
                            break;
                        case '%':
                            $escaped[] = NAUGHTY_ESCAPED;
                            break;
                        case '*':
                            $escaped[] = ENTITY_ESCAPED;
                            break;
                        case '=':
                            $escaped[] = FORCIBLY_ENTITY_ESCAPED;
                            break;
                        case ';':
                            $escaped[] = SQ_ESCAPED;
                            break;
                        case '#':
                            $escaped[] = DQ_ESCAPED;
                            break;
                        case '~':
                            $escaped[] = NL_ESCAPED;
                            break;
                        case '^':
                            $escaped[] = NL2_ESCAPED;
                            break;
                        case '|':
                            $escaped[] = ID_ESCAPED;
                            break;
                        case '\'':
                            $escaped[] = CSS_ESCAPED;
                            break;
                        case '&':
                            $escaped[] = UL_ESCAPED;
                            break;
                        case '.':
                            $escaped[] = UL2_ESCAPED;
                            break;
                        case '/':
                            $escaped[] = JSHTML_ESCAPED;
                            break;
                        case '@':
                            $escaped[] = CC_ESCAPED;
                            break;
                            // This is used as a hint to not preprocess
                        // This is used as a hint to not preprocess
                        case '-':
                    }
                }
                $_opener_params = '';
                foreach ($opener_params as $param) {
                    if ($param == array()) {
                        $param = array('""');
                    }
                    if ($_opener_params != '') {
                        $_opener_params .= ',';
                    }
                    $_opener_params .= implode('.', $param);
                }
                $first_param = str_replace(array('`', '%', '*', '=', ';', '#', '-', '~', '^', '|', '\'', '&', '.', '/', '@'), array('', '', '', '', '', '', '', '', '', '', '', '', '', '', ''), $_first_param);
                switch ($past_level_mode) {
                    case PARSE_SYMBOL:
                        $no_preprocess = in_array('-', $_escaped);
                        if (!$no_preprocess) {
                            switch ($first_param) {
                                case '"CSS_INCLUDE"':
                                case '"JAVASCRIPT_INCLUDE"':
                                case '"JS_TEMPCODE"':
                                case '"CSS_TEMPCODE"':
                                case '"SET"':
                                case '"BLOCK"':
                                case '"LOAD_PAGE"':
                                case '"LOAD_PANEL"':
                                    foreach ($stack as $level_test) {
                                        if ($level_test[3] == PARSE_DIRECTIVE && isset($level_test[5][1]) && isset($level_test[5][1][0]) && $level_test[5][1][0] == '"LOOP"') {
                                            $eval = @eval('return array(' . $_opener_params . ');');
                                            if (is_array($eval)) {
                                                $pp_bit = array(array(), TC_SYMBOL, str_replace('"', '', $first_param), $eval);
                                                $preprocessable_bits[] = $pp_bit;
                                            }
                                            break 2;
                                        }
                                    }
                                    $symbol_params = array();
                                    foreach ($opener_params as $param) {
                                        if ($param == array()) {
                                            $param = array('""');
                                        }
                                        $myfunc = 'tcpfunc_' . fast_uniqid();
                                        $funcdef = build_closure_function($myfunc, $param);
                                        $symbol_params[] = new ocp_tempcode(array($funcdef, array(array($myfunc, array(), TC_KNOWN, '', ''))));
                                        // Parameters will be bound in later.
                                    }
                                    $pp_bit = array(array(), TC_SYMBOL, str_replace('"', '', $first_param), $symbol_params);
                                    $preprocessable_bits[] = $pp_bit;
                                    break;
                            }
                        }
                        if ($first_param == '"IMG"' && strpos($_opener_params, ',') === false) {
                            $_opener_params .= ',"0","' . php_addslashes($theme) . '"';
                        }
                        if ($first_param == '"?"') {
                            if (implode('.', $opener_params[0]) == '"1".""') {
                                if (isset($opener_params[1])) {
                                    $current_level_data[] = implode('.', $opener_params[1]);
                                }
                                break;
                            }
                            if (implode('.', $opener_params[0]) == '"0".""' || implode('.', $opener_params[0]) == '""') {
                                if (isset($opener_params[2])) {
                                    $current_level_data[] = implode('.', $opener_params[2]);
                                }
                                break;
                            }
                        }
                        if ($first_param != '""') {
                            $new_line = 'ecv($cl,array(' . implode(',', $escaped) . '),' . strval(TC_SYMBOL) . ',' . $first_param . ',array(' . $_opener_params . '))';
                            if (in_array($first_param, $compilable_symbols) && preg_match('#^[^\\(\\)]*$#', $_opener_params) != 0) {
                                $new_line = '"' . php_addslashes(eval('return ' . $new_line . ';')) . '"';
                            }
                            $current_level_data[] = $new_line;
                        }
                        break;
                    case PARSE_LANGUAGE_REFERENCE:
                        $new_line = 'ecv($cl,array(' . implode(',', $escaped) . '),' . strval(TC_LANGUAGE_REFERENCE) . ',' . $first_param . ',array(' . $_opener_params . '))';
                        if ($_opener_params == '' && count($escaped) == 0) {
                            $looked_up = do_lang(eval('return ' . $first_param . ';'), NULL, NULL, NULL, $lang, false);
                            if (!is_null($looked_up)) {
                                if (apply_tempcode_escaping($escaped, $looked_up) == $looked_up) {
                                    $new_line = '"' . php_addslashes($looked_up) . '"';
                                }
                            }
                        }
                        $current_level_data[] = $new_line;
                        break;
                    case PARSE_PARAMETER:
                        $parameter = str_replace('"', '', str_replace("'", '', $first_param));
                        $parameter = preg_replace('#[^\\w\\_\\d]#', '', $parameter);
                        // security to stop PHP injection
                        $temp = 'output_tempcode_parameter( isset ($bound_' . php_addslashes($parameter) . ')?$bound_' . php_addslashes($parameter) . ':NULL,"' . php_addslashes($parameter) . '","' . php_addslashes($template_name) . '")';
                        if (count($escaped) == 0) {
                            $current_level_data[] = $temp;
                        } else {
                            $s_escaped = '';
                            foreach ($escaped as $esc) {
                                if ($s_escaped != '') {
                                    $s_escaped .= ',';
                                }
                                $s_escaped .= strval($esc);
                            }
                            if ($s_escaped == strval(ENTITY_ESCAPED) && !$GLOBALS['XSS_DETECT']) {
                                $current_level_data[] = '( isset ($bound_' . $parameter . ')?(((isset($bound_' . $parameter . '->preprocessable_bits)) && ($bound_' . $parameter . '->pure_lang))?' . $temp . ':str_replace($GLOBALS[\'HTML_ESCAPE_1_STRREP\'],$GLOBALS[\'HTML_ESCAPE_2\'],' . $temp . ')):attach_message(do_lang_tempcode(\'MISSING_TEMPLATE_PARAMETER\',"' . php_addslashes($parameter) . '","' . php_addslashes($template_name) . '"),"warn"))';
                            } else {
                                if ($s_escaped == strval(ENTITY_ESCAPED)) {
                                    $current_level_data[] = '( isset ($bound_' . $parameter . ')?(((isset($bound_' . $parameter . '->preprocessable_bits)) && ($bound_' . $parameter . '->pure_lang))?' . $temp . ':apply_tempcode_escaping_inline(array(' . $s_escaped . '),' . $temp . ')):attach_message(do_lang_tempcode(\'MISSING_TEMPLATE_PARAMETER\',"' . php_addslashes($parameter) . '","' . php_addslashes($template_name) . '"),"warn"))';
                                } else {
                                    $current_level_data[] = '( isset ($bound_' . $parameter . ')?apply_tempcode_escaping_inline(array(' . $s_escaped . '),' . $temp . '):attach_message(do_lang_tempcode(\'MISSING_TEMPLATE_PARAMETER\',"' . php_addslashes($parameter) . '","' . php_addslashes($template_name) . '"),"warn"))';
                                }
                            }
                        }
                        break;
                }
                // Handle directive nesting
                if ($past_level_mode == PARSE_DIRECTIVE) {
                    $eval = @eval('return ' . $first_param . ';');
                    if (!is_string($eval)) {
                        $eval = '';
                    }
                    if ($eval == 'START') {
                        // Open a new directive level
                        $stack[] = array($current_level_mode, $current_level_data, $current_level_params, $past_level_mode, $past_level_data, $past_level_params);
                        $current_level_data = array();
                        $current_level_params = array();
                        $current_level_mode = PARSE_DIRECTIVE_INNER;
                    } elseif ($eval == 'END') {
                        // Test that the top stack does represent a started directive, and close directive level
                        $past_level_data = $current_level_data;
                        if ($past_level_data == array()) {
                            $past_level_data = array('""');
                        }
                        $past_level_params = $current_level_params;
                        $past_level_mode = $current_level_mode;
                        if (count($stack) == 0) {
                            if ($tolerate_errors) {
                                continue;
                            }
                            warn_exit(do_lang_tempcode('TEMPCODE_TOO_MANY_CLOSES', escape_html($template_name), integer_format(1 + substr_count(substr($data, 0, _length_so_far($bits, $i)), chr(10)))));
                        }
                        list($current_level_mode, $current_level_data, $current_level_params, $directive_level_mode, $directive_level_data, $directive_level_params) = array_pop($stack);
                        if (!is_array($directive_level_params)) {
                            if ($tolerate_errors) {
                                continue;
                            }
                            warn_exit(do_lang_tempcode('UNCLOSED_DIRECTIVE_OR_BRACE', escape_html($template_name), integer_format(1 + substr_count(substr($data, 0, _length_so_far($bits, $i)), chr(10)))));
                        }
                        $directive_opener_params = array_merge($directive_level_params, array($directive_level_data));
                        if ($directive_level_mode != PARSE_DIRECTIVE || $directive_opener_params[0][0] != '"START"') {
                            if ($tolerate_errors) {
                                continue;
                            }
                            warn_exit(do_lang_tempcode('TEMPCODE_TOO_MANY_CLOSES', escape_html($template_name), integer_format(1 + substr_count(substr($data, 0, _length_so_far($bits, $i)), chr(10)))));
                        }
                        // Handle directive
                        if (count($directive_opener_params) == 1) {
                            if ($tolerate_errors) {
                                continue;
                            }
                            warn_exit(do_lang_tempcode('NO_DIRECTIVE_TYPE', escape_html($template_name), integer_format(1 + substr_count(substr($data, 0, _length_so_far($bits, $i)), chr(10)))));
                        }
                        $directive_params = '';
                        $first_directive_param = '""';
                        if ($directive_opener_params[1] == array()) {
                            $directive_opener_params[1] = array('""');
                        }
                        for ($j = 2; $j < count($directive_opener_params); $j++) {
                            if ($directive_opener_params[$j] == array()) {
                                $directive_opener_params[$j] = array('""');
                            }
                            if ($directive_params != '') {
                                $directive_params .= ',';
                            }
                            $directive_params .= implode('.', $directive_opener_params[$j]);
                            if ($j == 2) {
                                $first_directive_param = implode('.', $directive_opener_params[$j]);
                            }
                        }
                        $eval = @eval('return ' . implode('.', $directive_opener_params[1]) . ';');
                        if (!is_string($eval)) {
                            $eval = '';
                        }
                        $directive_name = $eval;
                        switch ($directive_name) {
                            case 'FRACTIONAL_EDITABLE':
                                $pp_bit = array(array(), TC_DIRECTIVE, str_replace('"', '', $directive_name), array());
                                $preprocessable_bits[] = $pp_bit;
                                break;
                        }
                        switch ($directive_name) {
                            case 'IF':
                                if (preg_match('#^ecv\\(\\$cl,array\\(\\),0,"NOT",array\\("1"\\)\\).""$#', $first_directive_param) != 0) {
                                    $first_directive_param = '"0".""';
                                }
                                if (preg_match('#^ecv\\(\\$cl,array\\(\\),0,"NOT",array\\("0"\\)\\).""$#', $first_directive_param) != 0) {
                                    $first_directive_param = '"1".""';
                                }
                                if ($first_directive_param == '"1".""') {
                                    $current_level_data[] = '(' . implode('.', $past_level_data) . ')';
                                } elseif ($first_directive_param != '"0".""') {
                                    $current_level_data[] = '((' . $first_directive_param . '=="1")?(' . implode('.', $past_level_data) . '):\'\')';
                                }
                                break;
                            case 'IF_EMPTY':
                                $current_level_data[] = '((' . $first_directive_param . '==\'\')?(' . implode('.', $past_level_data) . '):\'\')';
                                break;
                            case 'WHILE':
                                $current_level_data[] = 'closure_while_loop(array($parameters,$cl,$last_attach),' . chr(10) . 'create_function(\'$parameters,$cl,$last_attach\',"extract(\\$parameters,EXTR_PREFIX_ALL,\'bound\'); return (' . php_addslashes($first_directive_param) . ')==\\"1\\";"),' . chr(10) . 'create_function(\'$parameters,$cl,$last_attach\',"extract(\\$parameters,EXTR_PREFIX_ALL,\'bound\'); return ' . php_addslashes(implode('.', $past_level_data)) . ';"))';
                                break;
                            case 'PHP':
                                $current_level_data[] = 'closure_eval(' . implode('.', $past_level_data) . ',$parameters)';
                                break;
                            case 'LOOP':
                                $current_level_data[] = 'closure_loop(array(' . $directive_params . ',\'vars\'=>$parameters),array($parameters,$cl,$last_attach),' . chr(10) . 'create_function(\'$parameters,$cl,$last_attach\',"extract(\\$parameters,EXTR_PREFIX_ALL,\'bound\'); return ' . php_addslashes(implode('.', $past_level_data)) . ';"))';
                                break;
                            case 'IF_NON_EMPTY':
                                $current_level_data[] = '((' . $first_directive_param . '!=\'\')?(' . implode('.', $past_level_data) . '):\'\')';
                                break;
                            case 'IF_PASSED':
                                $eval = @eval('return ' . $first_directive_param . ';');
                                if (!is_string($eval)) {
                                    $eval = '';
                                }
                                $current_level_data[] = '(isset($bound_' . preg_replace('#[^\\w\\d\\_]#', '', $eval) . ')?(' . implode('.', $past_level_data) . '):\'\')';
                                break;
                            case 'IF_NON_PASSED':
                                $eval = @eval('return ' . $first_directive_param . ';');
                                if (!is_string($eval)) {
                                    $eval = '';
                                }
                                $current_level_data[] = '(!isset($bound_' . preg_replace('#[^\\w\\d\\_]#', '', $eval) . ')?(' . implode('.', $past_level_data) . '):\'\')';
                                break;
                            case 'IF_ADJACENT':
                                $current_level_data[] = '(($last_attach=="' . php_addslashes($template_name) . '")?(' . implode('.', $past_level_data) . '):\'\')';
                                break;
                            case 'IF_NON_ADJACENT':
                                $current_level_data[] = '(($last_attach!="' . php_addslashes($template_name) . '")?(' . implode('.', $past_level_data) . '):\'\')';
                                break;
                            case 'SHIFT_ENCODE':
                                $eval = @eval('return ' . implode('.', $directive_opener_params[2]) . ';');
                                if (!is_string($eval)) {
                                    $eval = '';
                                }
                                $key = $eval;
                                $set_op = '$GLOBALS[\'SHIFT_VARIABLES\']["' . php_addslashes($key) . '"]=make_string_tempcode(' . implode('.', $past_level_data) . ')';
                                if (array_key_exists(3, $directive_opener_params)) {
                                    $attach_op = '$GLOBALS[\'SHIFT_VARIABLES\']["' . php_addslashes($key) . '"]->attach(' . implode('.', $past_level_data) . ')';
                                    $is_set_check = 'array_key_exists("' . php_addslashes($key) . '",$GLOBALS[\'SHIFT_VARIABLES\'])';
                                    // NB: The "/*SHIFT_ENCODE*/" bit is critical, it's used as a marker for identifying the need for preexecution
                                    $current_level_data[] = '/*SHIFT_ENCODE*/(is_null(((!' . $is_set_check . ') || (' . implode('.', $directive_opener_params[3]) . '==\'0\'))' . '?' . $set_op . ':' . $attach_op . ')?\'\':\'\')';
                                } else {
                                    $current_level_data[] = '/*SHIFT_ENCODE*/(is_null(' . $set_op . ')?\'\':\'\')';
                                }
                                break;
                            case 'INCLUDE':
                                global $FILE_ARRAY;
                                if (count($directive_opener_params) == 3 && $past_level_data == array('""') && !isset($FILE_ARRAY)) {
                                    $eval = @eval('return ' . $first_directive_param . ';');
                                    if (!is_string($eval)) {
                                        $eval = '';
                                    }
                                    $found = find_template_place($eval, '', $theme, '.tpl', 'templates');
                                    $_theme = $found[0];
                                    $fullpath = get_custom_file_base() . '/themes/' . $_theme . $found[1] . $eval . '.tpl';
                                    if (!is_file($fullpath)) {
                                        $fullpath = get_file_base() . '/themes/' . $_theme . $found[1] . $eval . '.tpl';
                                    }
                                    $filecontents = @file_get_contents($fullpath, FILE_TEXT);
                                    if ($filecontents === false) {
                                        $filecontents = '';
                                    }
                                    list($_current_level_data, $_preprocessable_bits) = compile_template($filecontents, $eval, $theme, $lang);
                                    $current_level_data = array_merge($current_level_data, $_current_level_data);
                                    $preprocessable_bits = array_merge($preprocessable_bits, $_preprocessable_bits);
                                    break;
                                }
                            default:
                                if ($directive_params != '') {
                                    $directive_params .= ',';
                                }
                                $directive_params .= implode('.', $past_level_data);
                                if (isset($GLOBALS['DIRECTIVES_NEEDING_VARS'][$directive_name])) {
                                    $current_level_data[] = 'ecv($cl,array(),' . strval(TC_DIRECTIVE) . ',' . implode('.', $directive_opener_params[1]) . ',array(' . $directive_params . ',\'vars\'=>$parameters))';
                                } else {
                                    $current_level_data[] = 'ecv($cl,array(),' . strval(TC_DIRECTIVE) . ',' . implode('.', $directive_opener_params[1]) . ',array(' . $directive_params . '))';
                                }
                                break;
                        }
                    } else {
                        $eval = @eval('return ' . $first_param . ';');
                        if (!is_string($eval)) {
                            $eval = '';
                        }
                        $directive_name = $eval;
                        if (isset($GLOBALS['DIRECTIVES_NEEDING_VARS'][$directive_name])) {
                            $current_level_data[] = 'ecv($cl,array(' . implode(',', $escaped) . '),' . strval(TC_DIRECTIVE) . ',' . $first_param . ',array(' . $_opener_params . ',\'vars\'=>$parameters))';
                        } else {
                            $current_level_data[] = 'ecv($cl,array(' . implode(',', $escaped) . '),' . strval(TC_DIRECTIVE) . ',' . $first_param . ',array(' . $_opener_params . '))';
                        }
                    }
                }
                break;
            case ',':
                switch ($current_level_mode) {
                    case PARSE_NO_MANS_LAND:
                    case PARSE_DIRECTIVE_INNER:
                        $current_level_data[] = '\',\'';
                        break;
                    default:
                        $current_level_params[] = $current_level_data;
                        $current_level_data = array();
                        break;
                }
                break;
            default:
                $literal = php_addslashes(str_replace('\\,', ',', str_replace('\\}', '}', str_replace('\\{', '{', $next_token))));
                if ($GLOBALS['XSS_DETECT']) {
                    ocp_mark_as_escaped($literal);
                }
                $current_level_data[] = '"' . $literal . '"';
                break;
        }
    }
    if (!array_key_exists('LAX_COMCODE', $GLOBALS) || !$GLOBALS['LAX_COMCODE']) {
        if (count($stack) != 0) {
            if (!$tolerate_errors) {
                warn_exit(do_lang_tempcode('UNCLOSED_DIRECTIVE_OR_BRACE', escape_html($template_name), integer_format(1 + substr_count(substr($data, 0, _length_so_far($bits, $i)), chr(10)))));
            }
        }
    }
    return array($current_level_data, $preprocessable_bits);
}
Beispiel #16
0
/**
 * Render the OCF forumview.
 *
 * @param  ?integer	Forum ID (NULL: personal topics).
 * @param  string		The filter category (blank if no filter)
 * @param  integer	Maximum results to show
 * @param  integer	Offset for result showing
 * @param  AUTO_LINK	Virtual root
 * @param  ?MEMBER	The member to show personal topics of (NULL: not showing personal topics)
 * @return mixed		Either Tempcode (an interface that must be shown) or a Tuple: The main Tempcode, a title to use (also Tempcode), breadcrumbs (also Tempcode), the forum name (string). For a PT view, it is always a tuple, never raw Tempcode (as it can go inside a tabset).
 */
function ocf_render_forumview($id, $current_filter_cat, $max, $start, $root, $of_member_id)
{
    require_css('ocf');
    $type = is_null($id) ? 'pt' : 'misc';
    if ($type == 'pt') {
        if (is_guest()) {
            access_denied('NOT_AS_GUEST');
        }
        require_code('ocf_forumview_pt');
        $details = ocf_get_personal_topics($start, $max, $of_member_id);
        $root_forum_name = $GLOBALS['FORUM_DB']->query_value('f_forums', 'f_name', array('id' => $root));
        $tree = hyperlink(build_url(array('page' => '_SELF', 'id' => $root == db_get_first_id() ? NULL : $root), '_SELF'), escape_html($root_forum_name), false, false, do_lang_tempcode('GO_BACKWARDS_TO', $root_forum_name), NULL, NULL, 'up');
        $tree->attach(' &gt; ');
        $pt_username = $GLOBALS['FORUM_DRIVER']->get_username($of_member_id);
        if (is_null($pt_username)) {
            $pt_username = do_lang('UNKNOWN');
        }
        $tree->attach(do_lang_tempcode('PERSONAL_TOPICS_OF', escape_html($pt_username)));
        $details['name'] = do_lang_tempcode('PERSONAL_TOPICS_OF', escape_html($pt_username));
    } else {
        $GLOBALS['FEED_URL'] = find_script('backend') . '?mode=ocf_forumview&filter=' . strval($id);
        $details = ocf_get_forum_view($start, $max, $id);
        $tree = ocf_forum_breadcrumbs($id, $details['name'], $details['parent_forum']);
        if (array_key_exists('question', $details) && is_null(get_bot_type())) {
            // Was there a question answering attempt?
            $answer = post_param('answer', '-1#');
            if ($answer != '-1#') {
                if (strtolower(trim($answer)) == strtolower(trim($details['answer']))) {
                    if (!is_guest()) {
                        $GLOBALS['FORUM_DB']->query_insert('f_forum_intro_member', array('i_forum_id' => $id, 'i_member_id' => get_member()));
                    } else {
                        $GLOBALS['FORUM_DB']->query_insert('f_forum_intro_ip', array('i_forum_id' => $id, 'i_ip' => get_ip_address(3)));
                    }
                } else {
                    $url = get_self_url();
                    $title = get_page_title('INTRO_QUESTION');
                    return redirect_screen($title, $url, do_lang_tempcode('INTRO_ANSWER_INCORRECT'), false, 'warn');
                }
            } else {
                // Ask the question
                $title = get_page_title($details['answer'] == '' ? 'INTRO_NOTICE' : 'INTRO_QUESTION');
                $url = get_self_url();
                return do_template('OCF_FORUM_INTRO_QUESTION_SCREEN', array('ANSWER' => $details['answer'], 'TITLE' => $title, 'URL' => $url, 'QUESTION' => $details['question']));
            }
        }
    }
    if ($type == 'pt') {
        $forum_name = do_lang('PERSONAL_TOPICS');
    } else {
        $forum_name = $details['name'];
    }
    $may_mass_moderate = array_key_exists('may_move_topics', $details) || array_key_exists('may_delete_topics', $details);
    // Find categories
    $categories = new ocp_tempcode();
    if ($type != 'pt') {
        foreach ($details['categories'] as $best => $category) {
            if (array_key_exists('subforums', $category)) {
                // Subforums
                $forums = new ocp_tempcode();
                foreach ($category['subforums'] as $subforum) {
                    if (array_key_exists('last_topic_id', $subforum) && !is_null($subforum['last_topic_id'])) {
                        if (!is_null($subforum['last_member_id'])) {
                            if (!is_guest($subforum['last_member_id'])) {
                                //$colour=get_group_colour(ocf_get_member_primary_group($subforum['last_member_id']));
                                $poster = do_template('OCF_USER_MEMBER', array('_GUID' => '39r932rwefldjfldjlf', 'USERNAME' => $subforum['last_username'], 'PROFILE_URL' => $GLOBALS['FORUM_DRIVER']->member_profile_url($subforum['last_member_id'], false, true)));
                            } else {
                                $poster = protect_from_escaping(escape_html($subforum['last_username']));
                            }
                        } else {
                            $poster = do_lang_tempcode('NA_EM');
                        }
                        $topic_url = build_url(array('page' => 'topicview', 'id' => $subforum['last_topic_id'], 'type' => 'first_unread'), get_module_zone('topicview'));
                        $topic_url->attach('#first_unread');
                        $latest = do_template('OCF_FORUM_LATEST', array('_GUID' => 'dlfsdfkoewfdlfsldfk', 'DATE' => is_null($subforum['last_time']) ? do_lang_tempcode('NA_EM') : protect_from_escaping(escape_html(get_timezoned_date($subforum['last_time']))), 'DATE_RAW' => is_null($subforum['last_time']) ? '' : strval($subforum['last_time']), 'TOPIC_URL' => $topic_url, 'TOPIC_TITLE' => $subforum['last_title'] == '' ? do_lang_tempcode('NA') : $subforum['last_title'], 'POSTER' => $poster, 'MEMBER_ID' => is_null($subforum['last_member_id']) ? '' : strval($subforum['last_member_id']), 'ID' => strval($subforum['last_topic_id'])));
                    } elseif (array_key_exists('protected_last_post', $subforum)) {
                        $latest = do_lang_tempcode('PROTECTED_LAST_POST');
                    } else {
                        $latest = do_lang_tempcode('NO_POSTS_YET');
                    }
                    // Work out where the subforum URL is
                    if ($subforum['redirection'] != '' && !is_numeric($subforum['redirection'])) {
                        $subforum_url = $subforum['redirection'];
                        $subforum_num_posts = do_lang_tempcode('NA_EM');
                        $subforum_num_topics = do_lang_tempcode('NA_EM');
                        $latest = do_lang_tempcode('NA_EM');
                        $subforum['has_new'] = false;
                        $subforums = new ocp_tempcode();
                        $new_post_or_not = 'redirect';
                    } else {
                        if ($subforum['redirection'] != '') {
                            $subforum_url = build_url(array('page' => '_SELF', 'id' => $subforum['redirection']), '_SELF');
                            $new_post_or_not = $subforum['has_new'] ? 'new_posts_redirect' : 'no_new_posts_redirect';
                        } else {
                            $subforum_url = build_url(array('page' => '_SELF', 'id' => $subforum['id']), '_SELF');
                            $new_post_or_not = $subforum['has_new'] ? 'new_posts' : 'no_new_posts';
                        }
                        $subforum_num_posts = protect_from_escaping(escape_html(integer_format($subforum['num_posts'])));
                        $subforum_num_topics = protect_from_escaping(escape_html(integer_format($subforum['num_topics'])));
                        // Subsubforums
                        $subforums = new ocp_tempcode();
                        ksort($subforum['children']);
                        foreach ($subforum['children'] as $child) {
                            // Work out where the subsubforum url is
                            if (is_numeric($child['redirection'])) {
                                $link = hyperlink(build_url(array('page' => '_SELF', 'id' => $child['redirection']), '_SELF'), $child['name'], false, true);
                            } elseif ($child['redirection'] != '') {
                                $link = hyperlink($child['redirection'], $child['name'], false, true);
                            } else {
                                $link = hyperlink(build_url(array('page' => '_SELF', 'id' => $child['id']), '_SELF'), $child['name'], false, true);
                            }
                            if (!$subforums->is_empty()) {
                                $subforums->attach(do_lang_tempcode('LIST_SEP'));
                            }
                            $subforums->attach($link);
                        }
                    }
                    $edit_url = has_actual_page_access(get_member(), 'admin_ocf_forums') ? build_url(array('page' => 'admin_ocf_forums', 'type' => '_ed', 'id' => $subforum['id']), 'adminzone') : new ocp_tempcode();
                    $forum_rules_url = '';
                    $intro_question_url = '';
                    if (!$subforum['intro_question']->is_empty()) {
                        if ($subforum['intro_answer'] == '') {
                            $keep = keep_symbol(array());
                            $intro_rules_url = find_script('rules') . '?id=' . rawurlencode(strval($subforum['id'])) . $keep;
                        } else {
                            $keep = keep_symbol(array());
                            $intro_question_url = find_script('rules') . '?id=' . rawurlencode(strval($subforum['id'])) . $keep;
                        }
                    }
                    $forums->attach(do_template('OCF_FORUM_IN_CATEGORY', array('_GUID' => 'slkfjof9jlsdjcsd', 'ID' => strval($subforum['id']), 'NEW_POST_OR_NOT' => $new_post_or_not, 'LANG_NEW_POST_OR_NOT' => do_lang('POST_INDICATOR_' . $new_post_or_not), 'FORUM_NAME' => $subforum['name'], 'FORUM_URL' => $subforum_url, 'DESCRIPTION' => $subforum['description'], 'NUM_POSTS' => $subforum_num_posts, 'NUM_TOPICS' => $subforum_num_topics, 'LATEST' => $latest, 'SUBFORUMS' => $subforums, 'EDIT_URL' => $edit_url, 'FORUM_RULES_URL' => $forum_rules_url, 'INTRO_QUESTION_URL' => $intro_question_url)));
                }
                // Category itself
                if (!array_key_exists('expanded_by_default', $category) || $category['expanded_by_default'] == 1) {
                    $display = 'table';
                    $expand_type = 'contract';
                } else {
                    $display = 'none';
                    $expand_type = 'expand';
                }
                $category_description = $category['description'];
                $categories->attach(do_template('OCF_FORUM_CATEGORY', array('_GUID' => 'fc9bae42c680ea0162287e2ed3917bbe', 'CATEGORY_ID' => strval($best), 'EXPAND_TYPE' => $expand_type, 'DISPLAY' => $display, 'CATEGORY_TITLE' => $category['title'], 'CATEGORY_DESCRIPTION' => $category_description, 'FORUMS' => $forums)));
            }
        }
    }
    // Work out what moderator actions can be performed (also includes marking read/unread)
    $moderator_actions = '';
    if ($type == 'pt' && $of_member_id == get_member() && get_value('disable_pt_filtering') !== '1') {
        $moderator_actions .= '<option value="categorise_pts">' . do_lang('CATEGORISE_PTS') . '</option>';
    }
    if (get_value('disable_mark_forum_read') !== '1') {
        $moderator_actions .= '<option value="mark_topics_read">' . do_lang('MARK_READ') . '</option>';
        $moderator_actions .= '<option value="mark_topics_unread">' . do_lang('MARK_UNREAD') . '</option>';
    }
    // Mass moderation
    if ($may_mass_moderate) {
        $moderator_actions .= '<option value="move_topics">' . do_lang('MOVE_TOPICS') . '</option>';
        if (has_specific_permission(get_member(), 'delete_midrange_content', 'topics', array('forums', $id))) {
            $moderator_actions .= '<option value="delete_topics">' . do_lang('DELETE_TOPICS') . '</option>';
        }
        $moderator_actions .= '<option value="pin_topics">' . do_lang('PIN_TOPIC') . '</option>';
        $moderator_actions .= '<option value="unpin_topics">' . do_lang('UNPIN_TOPIC') . '</option>';
        $moderator_actions .= '<option value="sink_topics">' . do_lang('SINK_TOPIC') . '</option>';
        $moderator_actions .= '<option value="unsink_topics">' . do_lang('UNSINK_TOPIC') . '</option>';
        $moderator_actions .= '<option value="cascade_topics">' . do_lang('CASCADE_TOPIC') . '</option>';
        $moderator_actions .= '<option value="uncascade_topics">' . do_lang('UNCASCADE_TOPIC') . '</option>';
        $moderator_actions .= '<option value="open_topics">' . do_lang('OPEN_TOPIC') . '</option>';
        $moderator_actions .= '<option value="close_topics">' . do_lang('CLOSE_TOPIC') . '</option>';
        if (!is_null($id)) {
            $multi_moderations = ocf_list_multi_moderations($id);
            if (count($multi_moderations) != 0) {
                $moderator_actions .= '<optgroup label="' . do_lang('MULTI_MODERATIONS') . '">';
                foreach ($multi_moderations as $mm_id => $mm_name) {
                    $moderator_actions .= '<option value="mmt_' . strval($mm_id) . '">' . $mm_name . '</option>';
                }
                $moderator_actions .= '</optgroup>';
            }
        }
    }
    // Find topics
    $topics = new ocp_tempcode();
    $pinned = false;
    $num_unread = 0;
    foreach ($details['topics'] as $topic) {
        if ($pinned && !in_array('pinned', $topic['modifiers'])) {
            $topics->attach(do_template('OCF_PINNED_DIVIDER'));
        }
        $pinned = in_array('pinned', $topic['modifiers']);
        $topics->attach(ocf_render_topic($topic, $moderator_actions != '', $type == 'pt', NULL));
        if (in_array('unread', $topic['modifiers'])) {
            $num_unread++;
        }
    }
    // Buttons
    $button_array = array();
    if (!is_guest() && $type != 'pt') {
        if (get_value('disable_mark_forum_read') !== '1') {
            $read_url = build_url(array('page' => 'topics', 'type' => 'mark_read', 'id' => $id), get_module_zone('topics'));
            $button_array[] = array('immediate' => true, 'title' => do_lang_tempcode('MARK_READ'), 'url' => $read_url, 'img' => 'mark_read');
        }
    }
    if ($type != 'pt') {
        if (addon_installed('search')) {
            $search_url = build_url(array('page' => 'search', 'type' => 'misc', 'id' => 'ocf_posts', 'search_under' => $id), get_module_zone('search'));
            $button_array[] = array('immediate' => false, 'rel' => 'search', 'title' => do_lang_tempcode('SEARCH'), 'url' => $search_url, 'img' => 'search');
        }
        $new_topic_url = build_url(array('page' => 'topics', 'type' => 'new_topic', 'id' => $id), get_module_zone('topics'));
    } else {
        if (addon_installed('search')) {
            $search_url = build_url(array('page' => 'search', 'type' => 'misc', 'id' => 'ocf_own_pt'), get_module_zone('search'));
            $button_array[] = array('immediate' => false, 'rel' => 'search', 'title' => do_lang_tempcode('SEARCH'), 'url' => $search_url, 'img' => 'search');
        }
        $new_topic_url = build_url(array('page' => 'topics', 'type' => 'new_pt', 'id' => get_member()), get_module_zone('topics'));
    }
    if ($type == 'pt') {
        //$archive_url=$GLOBALS['FORUM_DRIVER']->forum_url(db_get_first_id());
        //$button_array[]=array('immediate'=>false,'title'=>do_lang_tempcode('ROOT_FORUM'),'url'=>$archive_url,'img'=>'forum');
    }
    if (array_key_exists('may_post_topic', $details)) {
        if ($type == 'pt') {
            $button_array[] = array('immediate' => false, 'rel' => 'add', 'title' => do_lang_tempcode('ADD_PERSONAL_TOPIC'), 'url' => $new_topic_url, 'img' => 'send_message');
        } else {
            $button_array[] = array('immediate' => false, 'rel' => 'add', 'title' => do_lang_tempcode('ADD_TOPIC'), 'url' => $new_topic_url, 'img' => 'new_topic');
        }
    }
    $buttons = ocf_screen_button_wrap($button_array);
    $starter_title = $type == 'pt' ? do_lang_tempcode('WITH_TITLING') : new ocp_tempcode();
    // Wrap it all up
    $action_url = build_url(array('page' => 'topics'), get_module_zone('topics'), NULL, false, true);
    if (!$topics->is_empty()) {
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($moderator_actions);
        }
        require_code('templates_results_browser');
        $results_browser = results_browser(do_lang_tempcode('FORUM_TOPICS'), $type == 'pt' ? $of_member_id : $id, $start, 'start', $max, 'max', $details['max_rows'], NULL, $type == 'pt' && get_page_name() != 'forumview' ? 'view' : $type, true, false, 7, NULL, $type == 'pt' && get_page_name() != 'forumview' ? 'tab__pts' : '');
        $order = array_key_exists('order', $details) ? $details['order'] : 'last_post';
        $topic_wrapper = do_template('OCF_FORUM_TOPIC_WRAPPER', array('_GUID' => 'e452b81001e5c6b7adb4d82e627bf983', 'TYPE' => $type, 'ID' => is_null($id) ? NULL : strval($id), 'MAX' => strval($max), 'ORDER' => $order, 'MAY_CHANGE_MAX' => array_key_exists('may_change_max', $details), 'ACTION_URL' => $action_url, 'BUTTONS' => $buttons, 'STARTER_TITLE' => $starter_title, 'TREE' => $tree, 'RESULTS_BROWSER' => $results_browser, 'MODERATOR_ACTIONS' => $moderator_actions, 'TOPICS' => $topics, 'FORUM_NAME' => $forum_name));
    } else {
        $topic_wrapper = new ocp_tempcode();
        $moderator_actions = '';
    }
    // Filters
    $filters = new ocp_tempcode();
    if (get_value('disable_pt_filtering') !== '1') {
        if ($type == 'pt') {
            $filter_cats = ocf_get_filter_cats(true);
            $filters_arr = array();
            foreach ($filter_cats as $fi => $filter_cat) {
                if ($filter_cat != '') {
                    $filtered_url = build_url(array('page' => '_SELF', 'category' => $filter_cat), '_SELF', NULL, true, false, false, 'tab__pts');
                    $filter_active = $filter_cat == $current_filter_cat;
                    $filters_arr[] = array('URL' => $filter_active ? new ocp_tempcode() : $filtered_url, 'CAPTION' => $filter_cat, 'HAS_NEXT' => isset($filter_cats[$fi + 1]));
                }
            }
            $filters = do_template('OCF_PT_FILTERS', array('FILTERS' => $filters_arr, 'RESET_URL' => build_url(array('page' => '_SELF', 'category' => NULL), '_SELF', NULL, true)));
        }
    }
    $map = array('_GUID' => '1c14afd9265b1bf69375169dd6faf83c', 'STARTER_TITLE' => $starter_title, 'ID' => is_null($id) ? NULL : strval($id), 'DESCRIPTION' => array_key_exists('description', $details) ? $details['description'] : '', 'FILTERS' => $filters, 'BUTTONS' => $buttons, 'TOPIC_WRAPPER' => $topic_wrapper, 'TREE' => $tree, 'CATEGORIES' => $categories);
    $content = do_template('OCF_FORUM', $map);
    $ltitle = do_lang_tempcode('NAMED_FORUM', escape_html($details['name']));
    return array($content, $ltitle, $tree, $forum_name);
}
Beispiel #17
0
/**
 * Get a nice, formatted XHTML list of gallery entries, in gallery tree structure
 *
 * @param  ID_TEXT		The table we are working with
 * @set    images videos
 * @param  ?ID_TEXT		The currently selected entry (NULL: none selected)
 * @param  ?AUTO_LINK	Only show images/videos submitted by this member (NULL: no filter)
 * @param  boolean		Whether to get a list of child galleries (not just direct ones, recursively), instead of just IDs
 * @param  boolean		Whether to only show for what may be edited by the current member
 * @return tempcode		The list of entries
 */
function nice_get_gallery_content_tree($table, $it = NULL, $submitter = NULL, $use_compound_list = false, $editable_filter = false)
{
    $tree = get_gallery_content_tree($table, $submitter, NULL, NULL, NULL, NULL, $use_compound_list, $editable_filter);
    if ($use_compound_list) {
        $tree = $tree[0];
    }
    $out = '';
    // XHTMLXHTML
    foreach ($tree as $gallery) {
        foreach ($gallery['entries'] as $eid => $etitle) {
            $selected = $eid == $it;
            $line = do_template('GALLERY_ENTRY_LIST_LINE', array('_GUID' => '5a6fac8a768e049f9cc6c2d4ec77eeca', 'TREE' => $gallery['tree'], 'URL' => $etitle));
            $out .= '<option value="' . (!$use_compound_list ? strval($eid) : $gallery['compound_list']) . '"' . ($selected ? 'selected="selected"' : '') . '>' . $line->evaluate() . '</option>';
        }
    }
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($out);
    }
    return make_string_tempcode($out);
}
 /**
  * The UI to set privileges.
  *
  * @return tempcode		The UI
  */
 function interface_specific_permissions()
 {
     require_all_lang();
     require_code('zones2');
     $title = get_page_title('SPECIFIC_PERMISSIONS');
     $p_section = get_param('id', NULL);
     if (is_null($p_section) || $p_section == '') {
         $GLOBALS['HELPER_PANEL_PIC'] = 'pagepics/privileges';
         $GLOBALS['HELPER_PANEL_TUTORIAL'] = 'tut_permissions';
         $GLOBALS['HELPER_PANEL_PIC'] = 'pagepics/privileges';
         $fields = new ocp_tempcode();
         require_code('form_templates');
         $_sections = $this->_get_ordered_sections();
         $sections = new ocp_tempcode();
         foreach ($_sections as $s) {
             if (is_null($s)) {
                 $sections->attach(form_input_list_entry('', false, '', false, true));
             } else {
                 if (!is_null($s['trans'])) {
                     $sections->attach(form_input_list_entry($s['p_section'], false, $s['trans']));
                 }
             }
         }
         $fields->attach(form_input_list(do_lang_tempcode('SECTION'), '', 'id', $sections, NULL, true));
         $post_url = get_self_url(false, false, NULL, false, true);
         return do_template('FORM_SCREEN', array('_GUID' => 'e5d457a49a76706afebc92da3d846e74', 'GET' => true, 'SKIP_VALIDATION' => true, 'HIDDEN' => '', 'SUBMIT_NAME' => do_lang_tempcode('CHOOSE'), 'TITLE' => $title, 'FIELDS' => $fields, 'URL' => $post_url, 'TEXT' => ''));
     }
     $title = get_page_title('_SPECIFIC_PERMISSIONS', true, array(do_lang_tempcode($p_section)));
     $url = build_url(array('page' => '_SELF', 'type' => '_specific', 'id' => $p_section), '_SELF');
     $admin_groups = $GLOBALS['FORUM_DRIVER']->get_super_admin_groups();
     $moderator_groups = $GLOBALS['FORUM_DRIVER']->get_moderator_groups();
     $groups = $GLOBALS['FORUM_DRIVER']->get_usergroup_list(false, true);
     $header_cells = $this->_access_header($admin_groups, $groups);
     $cols = new ocp_tempcode();
     foreach ($groups as $id => $g_name) {
         if (in_array($id, $admin_groups)) {
             continue;
         }
         $cols->attach(do_template('PERMISSION_COLUMN_SIZER'));
     }
     // Find all module permission overrides
     $all_module_overrides = array();
     foreach (find_all_zones() as $zone) {
         $all_modules = array();
         $all_modules += find_all_pages($zone, 'modules_custom', 'php', false);
         $all_modules += find_all_pages($zone, 'modules', 'php', false);
         foreach ($all_modules as $module => $module_type) {
             $functions = extract_module_functions(zone_black_magic_filterer(get_file_base() . '/' . $zone . ($zone == '' ? '' : '/') . 'pages/' . $module_type . '/' . $module . '.php'), array('get_sp_overrides'));
             if (!is_null($functions[0])) {
                 $overrides = is_array($functions[0]) ? call_user_func_array($functions[0][0], $functions[0][1]) : eval($functions[0]);
                 foreach (array_keys($overrides) as $override) {
                     if (!array_key_exists($override, $all_module_overrides)) {
                         $all_module_overrides[$override] = array();
                     }
                     $all_module_overrides[$override][] = $module;
                 }
             }
         }
     }
     $all_page_permission_overridding = $GLOBALS['SITE_DB']->query_select('gsp', array('the_page', 'specific_permission'), array('category_name' => ''));
     // Rows (pages)
     $rows = new ocp_tempcode();
     $where = array('p_section' => $p_section);
     // Added in because it was eating up too much memory
     $_permissions = collapse_2d_complexity('the_name', 'p_section', $GLOBALS['SITE_DB']->query_select('sp_list', array('p_section', 'the_name'), $where, 'ORDER BY p_section,the_name'));
     $access_rows = $GLOBALS['SITE_DB']->query_select('gsp', array('specific_permission', 'group_id'), array('the_page' => '', 'module_the_name' => '', 'category_name' => ''));
     $current_section = '';
     $sections = new ocp_tempcode();
     $_false = do_template('PERMISSION_CELL', array('_GUID' => '61aa7fa739e19caa1efb3695a5e2ab5d', 'CHECKED' => false, 'HUMAN' => '__human__', 'NAME' => '__name__'));
     $_true = do_template('PERMISSION_CELL', array('_GUID' => '44a888b40d7a34aed6ed2bf8ff47f1de', 'CHECKED' => true, 'HUMAN' => '__human__', 'NAME' => '__name__'));
     $true = $_true->evaluate();
     $false = $_false->evaluate();
     // Ad-hoc sorting?
     $orderings = array('submit_low', 'edit_own_low', 'edit_low', 'delete_own_low', 'delete_low', 'bypass_validation_low', 'submit_mid', 'edit_own_mid', 'edit_mid', 'delete_own_mid', 'delete_mid', 'bypass_validation_mid', 'submit_high', 'edit_own_high', 'edit_high', 'delete_own_high', 'delete_high', 'bypass_validation_high', 'submit_cat_low', 'edit_own_cat_low', 'edit_cat_low', 'delete_own_cat_low', 'delete_cat_low', 'bypass_cat_validation_low', 'submit_cat_mid', 'edit_own_cat_mid', 'edit_cat_mid', 'delete_own_cat_mid', 'delete_cat_mid', 'bypass_cat_validation_mid', 'submit_cat_high', 'edit_own_cat_high', 'edit_cat_high', 'delete_own_cat_high', 'delete_cat_high', 'bypass_cat_validation_high');
     $permissions_first = array();
     foreach ($orderings as $stub) {
         foreach ($_permissions as $permission => $section) {
             if (substr($permission, 0, strlen($stub)) == $stub) {
                 $permissions_first[$permission] = $section;
                 unset($_permissions[$permission]);
             }
         }
     }
     $_permissions = array_merge($permissions_first, $_permissions);
     // Display
     foreach ($_permissions as $permission => $section) {
         $permission_text = do_lang('PT_' . $permission, NULL, NULL, NULL, NULL, false);
         if (is_null($permission_text)) {
             continue;
         }
         if ($section != $current_section && $current_section != '') {
             $sections->attach(do_template('PERMISSION_S_CONFIG_SECTION', array('_GUID' => '36bc9dfbeb7ee3d91f2a18057cd30551', 'HEADER_CELLS' => $header_cells, 'SECTION' => $rows, 'CURRENT_SECTION' => do_lang_tempcode($current_section))));
             $rows = new ocp_tempcode();
         }
         $cells = '';
         $code = '';
         $has = true;
         foreach ($groups as $id => $g_name) {
             if (in_array($id, $admin_groups)) {
                 continue;
             }
             $has_permission = false;
             foreach ($access_rows as $access_row) {
                 if ($access_row['specific_permission'] == $permission && $access_row['group_id'] == $id) {
                     $has_permission = true;
                     break;
                 }
             }
             if (!$has_permission) {
                 $has = false;
             }
             $cells .= str_replace('__human__', escape_html(addslashes(do_lang('PERMISSION_CELL', $permission_text, $g_name))), str_replace('__name__', $permission . '__' . strval($id), $has_permission ? $true : $false));
             if (in_array($id, $moderator_groups)) {
                 $code .= 'form.elements[\'' . $permission . '__' . strval($id) . '\'].checked=true;';
             } else {
                 $code .= 'form.elements[\'' . $permission . '__' . strval($id) . '\'].checked=this.value==\'+\';';
             }
         }
         if ($GLOBALS['XSS_DETECT']) {
             ocp_mark_as_escaped($cells);
         }
         $tpl_map = array('_GUID' => '075f8855f0fed36b0d0f9c61108dd3de', 'HAS' => $has, 'ABBR' => $permission, 'PERMISSION' => $permission_text, 'CELLS' => $cells, 'CODE' => $code);
         // See if any modules can override this
         if (array_key_exists($permission, $all_module_overrides)) {
             $m_list = '';
             $has_actual_overriding = false;
             foreach ($all_module_overrides[$permission] as $module) {
                 $this_overrides = false;
                 foreach ($all_page_permission_overridding as $po_row) {
                     if ($po_row['the_page'] == $module && $po_row['specific_permission'] == $permission) {
                         $this_overrides = true;
                         break;
                     }
                 }
                 if ($m_list != '') {
                     $m_list .= escape_html(', ');
                 }
                 if ($this_overrides) {
                     $has_actual_overriding = true;
                     $m_list .= '<s>' . escape_html($module) . '</s>';
                 } else {
                     $m_list .= '<strong>' . escape_html($module) . '</strong>';
                 }
                 if ($module == 'topics') {
                     $m_list .= ' (' . strtolower(do_lang(strpos($permission, 'lowrange') !== false ? 'FORUM_POSTS' : 'FORUM_TOPICS')) . ')';
                 }
             }
             if (function_exists('ocp_mark_as_escaped')) {
                 ocp_mark_as_escaped($m_list);
             }
             $tpl_map['DESCRIPTION'] = do_lang_tempcode($has_actual_overriding ? 'SP_USED_IN_SLASHED' : 'SP_USED_IN', $m_list);
         }
         // Render row
         $rows->attach(do_template('PERMISSION_ROW', $tpl_map));
         $current_section = $section;
     }
     $sections->attach(do_template('PERMISSION_S_CONFIG_SECTION', array('_GUID' => 'c75a07373f54c0fa31d18e360fcf26f6', 'COLS' => $cols, 'HEADER_CELLS' => $header_cells, 'SECTION' => $rows, 'CURRENT_SECTION' => do_lang_tempcode($current_section))));
     breadcrumb_set_parents(array(array('_SELF:_SELF:specific', do_lang_tempcode('CHOOSE'))));
     return do_template('PERMISSION_S_PERMISSIONS_SCREEN', array('_GUID' => '11974f0a137266a625991d3611b8e587', 'TITLE' => $title, 'URL' => $url, 'SECTIONS' => $sections));
 }
Beispiel #19
0
 /**
  * This function is a very basic query executor. It shouldn't usually be used by you, as there are abstracted versions available.
  *
  * @param  string			The complete SQL query
  * @param  array			A DB connection
  * @param  ?integer		The maximum number of rows to affect (NULL: no limit)
  * @param  ?integer		The start row to affect (NULL: no specification)
  * @param  boolean		Whether to output an error on failure
  * @param  boolean		Whether to get the autoincrement ID created for an insert query
  * @return ?mixed			The results (NULL: no results), or the insert ID
  */
 function db_query($query, $db, $max = NULL, $start = NULL, $fail_ok = false, $get_insert_id = false)
 {
     if (strtoupper(substr($query, 0, 7)) == 'SELECT ') {
         if (!is_null($max) && !is_null($start)) {
             $query .= ' LIMIT ' . strval(intval($max)) . ' OFFSET ' . strval(intval($start));
         } elseif (!is_null($max)) {
             $query .= ' LIMIT ' . strval(intval($max));
         } elseif (!is_null($start)) {
             $query .= ' OFFSET ' . strval(intval($start));
         }
     }
     $results = @pg_query($db, $query);
     if (($results === false || strtoupper(substr($query, 0, 7)) == 'SELECT ' && $results === true) && !$fail_ok) {
         $err = pg_last_error($db);
         if (function_exists('ocp_mark_as_escaped')) {
             ocp_mark_as_escaped($err);
         }
         if (!running_script('upgrader') && get_page_name() != 'admin_import') {
             if (!function_exists('do_lang') || is_null(do_lang('QUERY_FAILED', NULL, NULL, NULL, NULL, false))) {
                 fatal_exit(htmlentities('Query failed: ' . $query . ' : ' . $err));
             }
             fatal_exit(do_lang_tempcode('QUERY_FAILED', escape_html($query), $err));
         } else {
             echo htmlentities('Database query failed: ' . $query . ' [') . $err . htmlentities(']' . '<br />' . chr(10));
             return NULL;
         }
     }
     if (strtoupper(substr($query, 0, 7)) == 'SELECT ' && $results !== false && $results !== true) {
         return $this->db_get_query_rows($results);
     }
     if ($get_insert_id) {
         if (strtoupper(substr($query, 0, 7)) == 'UPDATE ') {
             return NULL;
         }
         // Inefficient :(
         $pos = strpos($query, '(');
         $table_name = substr($query, 12, $pos - 13);
         $r3 = @pg_query($db, 'SELECT last_value FROM ' . $table_name . '_id_seq');
         if ($r3) {
             $seq_array = pg_fetch_row($r3, 0);
             return intval($seq_array[0]);
         }
     }
     return NULL;
 }
Beispiel #20
0
 /**
  * The UI to show a virtual forum.
  *
  * @param  SHORT_TEXT	The title to show for the v-forum
  * @param  mixed			The condition (a fragment of an SQL query that gets embedded in the context of a topic selection query). May be string, or array of strings (separate queries to run and merge; done for performance reasons relating to DB indexing)
  * @param  string			The ordering of the results
  * @param  boolean		Whether to not show pinning in a separate section
  * @return tempcode		The UI
  */
 function _vforum($title, $condition, $order, $no_pin = false)
 {
     $max = get_param_integer('max', intval(get_option('forum_topics_per_page')));
     $start = get_param_integer('start', 0);
     $type = get_param('type', 'misc');
     $forum_name = do_lang_tempcode('VIRTUAL_FORUM');
     // Find topics
     $extra = '';
     if (!has_specific_permission(get_member(), 'see_unvalidated')) {
         $extra = 't_validated=1';
     }
     if (!$GLOBALS['FORUM_DRIVER']->is_super_admin(get_member())) {
         $groups = $GLOBALS['FORUM_DRIVER']->get_members_groups(get_member(), false, true);
         $group_or_list = '';
         foreach ($groups as $group) {
             if ($group_or_list != '') {
                 $group_or_list .= ' OR ';
             }
             $group_or_list .= 'group_id=' . strval((int) $group);
         }
         if ($extra != '') {
             $extra .= ' AND ';
         }
         $or_list = '';
         global $SITE_INFO;
         if (isset($SITE_INFO['mysql_old']) && $SITE_INFO['mysql_old'] == '1' || !isset($SITE_INFO['mysql_old']) && is_file(get_file_base() . '/mysql_old')) {
             $forum_access = $GLOBALS['FORUM_DB']->query('SELECT category_name FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'group_category_access WHERE (' . $group_or_list . ') AND ' . db_string_equal_to('module_the_name', 'forums'), NULL, NULL, false, true);
         } else {
             $forum_access = $GLOBALS['FORUM_DB']->query('SELECT category_name FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'group_category_access WHERE (' . $group_or_list . ') AND ' . db_string_equal_to('module_the_name', 'forums') . ' UNION ALL SELECT category_name FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'member_category_access WHERE (member_id=' . strval((int) get_member()) . ' AND active_until>' . strval(time()) . ') AND ' . db_string_equal_to('module_the_name', 'forums'), NULL, NULL, false, true);
         }
         foreach ($forum_access as $access) {
             if ($or_list != '') {
                 $or_list .= ' OR ';
             }
             $or_list .= 't_forum_id=' . strval((int) $access['category_name']);
         }
         $extra .= '(' . $or_list . ')';
     }
     if ($extra != '') {
         $extra = ' AND (' . $extra . ') ';
     }
     $max_rows = 0;
     $topic_rows = array();
     foreach (is_array($condition) ? $condition : array($condition) as $_condition) {
         $query = ' FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_topics top LEFT JOIN ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_read_logs l ON (top.id=l.l_topic_id AND l.l_member_id=' . strval((int) get_member()) . ') LEFT JOIN ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'translate t ON ' . db_string_equal_to('language', user_lang()) . ' AND top.t_cache_first_post=t.id WHERE ((' . $_condition . ')' . $extra . ') AND t_forum_id IS NOT NULL ORDER BY ' . $order;
         $topic_rows = array_merge($topic_rows, $GLOBALS['FORUM_DB']->query('SELECT top.*,t.text_parsed AS _trans_post,l_time' . $query, $max, $start));
         //if (($start==0) && (count($topic_rows)<$max)) $max_rows+=$max; // We know that they're all on this screen
         /*else */
         $max_rows += $GLOBALS['FORUM_DB']->query_value_null_ok_full('SELECT COUNT(*) ' . $query);
     }
     $hot_topic_definition = intval(get_option('hot_topic_definition'));
     $or_list = '';
     foreach ($topic_rows as $topic_row) {
         if ($or_list != '') {
             $or_list .= ' OR ';
         }
         $or_list .= 'p_topic_id=' . strval((int) $topic_row['id']);
     }
     if ($or_list != '') {
         $involved = $GLOBALS['FORUM_DB']->query('SELECT DISTINCT p_topic_id FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_posts WHERE (' . $or_list . ') AND p_poster=' . strval((int) get_member()));
         $involved = collapse_1d_complexity('p_topic_id', $involved);
     }
     $topics_array = array();
     foreach ($topic_rows as $topic_row) {
         $topics_array[] = ocf_get_topic_array($topic_row, get_member(), $hot_topic_definition, in_array($topic_row['id'], $involved));
     }
     // Display topics
     $topics = new ocp_tempcode();
     $pinned = false;
     require_code('templates_results_browser');
     $topic_wrapper = new ocp_tempcode();
     $forum_name_map = collapse_2d_complexity('id', 'f_name', $GLOBALS['FORUM_DB']->query('SELECT id,f_name FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_forums WHERE f_cache_num_posts>0'));
     foreach ($topics_array as $topic) {
         if (!$no_pin && $pinned && !in_array('pinned', $topic['modifiers'])) {
             $topics->attach(do_template('OCF_PINNED_DIVIDER'));
         }
         $pinned = in_array('pinned', $topic['modifiers']);
         $forum_id = array_key_exists('forum_id', $topic) ? $topic['forum_id'] : NULL;
         $_forum_name = array_key_exists($forum_id, $forum_name_map) ? $forum_name_map[$forum_id] : do_lang_tempcode('PERSONAL_TOPICS');
         $topics->attach(ocf_render_topic($topic, true, false, $_forum_name));
     }
     $tree = ocf_forum_breadcrumbs(db_get_first_id(), $title, get_param_integer('keep_forum_root', db_get_first_id()));
     if (!$topics->is_empty()) {
         $results_browser = results_browser(do_lang_tempcode('FORUM_TOPICS'), NULL, $start, 'start', $max, 'max', $max_rows, NULL, $type, true);
         $moderator_actions = '';
         $moderator_actions .= '<option value="mark_topics_read">' . do_lang('MARK_READ') . '</option>';
         if ($title != do_lang('TOPICS_UNREAD')) {
             $moderator_actions .= '<option value="mark_topics_unread">' . do_lang('MARK_UNREAD') . '</option>';
         }
         if ($GLOBALS['XSS_DETECT']) {
             ocp_mark_as_escaped($moderator_actions);
         }
         $action_url = build_url(array('page' => 'topics', 'redirect' => get_self_url(true)), get_module_zone('topics'));
         $topic_wrapper = do_template('OCF_FORUM_TOPIC_WRAPPER', array('_GUID' => '67356b4daacbed3e3d960d89a57d0a4a', 'MAX' => strval($max), 'ORDER' => '', 'MAY_CHANGE_MAX' => false, 'TREE' => $tree, 'BUTTONS' => '', 'STARTER_TITLE' => '', 'RESULTS_BROWSER' => $results_browser, 'MODERATOR_ACTIONS' => $moderator_actions, 'ACTION_URL' => $action_url, 'TOPICS' => $topics, 'FORUM_NAME' => $forum_name));
     }
     $_buttons = new ocp_tempcode();
     $archive_url = $GLOBALS['FORUM_DRIVER']->forum_url(db_get_first_id(), true);
     $_buttons->attach(do_template('SCREEN_BUTTON', array('TITLE' => do_lang_tempcode('ROOT_FORUM'), 'IMG' => 'all', 'IMMEDIATE' => false, 'URL' => $archive_url)));
     breadcrumb_add_segment($tree);
     return do_template('OCF_FORUM', array('_GUID' => 'd3fa84575727af935eadb2ce2b7c7b3e', 'FILTERS' => '', 'FORUM_NAME' => $forum_name, 'STARTER_TITLE' => '', 'BUTTONS' => $_buttons, 'TOPIC_WRAPPER' => $topic_wrapper, 'CATEGORIES' => ''));
 }
Beispiel #21
0
/**
 * This is it - the start of rendering of a website page.
 * Take in all inputs, sends them to the correct functions to process, gathers up all the outputs, sticks them together and echoes them.
 */
function do_site()
{
    // More SEO redirection (monikers)
    // Does this URL arrangement support monikers?
    $url_id = get_param('id', NULL, true);
    if ($url_id !== NULL && url_monikers_enabled()) {
        $type = get_param('type', 'misc');
        $looking_for = '_SEARCH:' . get_page_name() . ':' . $type . ':_WILD';
        $hooks = find_all_hooks('systems', 'content_meta_aware');
        $ob_info = NULL;
        foreach (array_keys($hooks) as $hook) {
            require_code('hooks/systems/content_meta_aware/' . filter_naughty($hook));
            $ob = object_factory('Hook_content_meta_aware_' . $hook, true);
            if ($ob === NULL) {
                continue;
            }
            $ob_info = $ob->info();
            $ob_info['view_pagelink_pattern'] = preg_replace('#:[^:]*$#', ':_WILD', $ob_info['view_pagelink_pattern']);
            if ($ob_info['view_pagelink_pattern'] == $looking_for && $ob_info['support_url_monikers']) {
                if (is_numeric($url_id)) {
                    $correct_moniker = find_id_moniker(array('page' => get_page_name(), 'type' => get_param('type', 'misc'), 'id' => $url_id));
                    if ($correct_moniker !== NULL && $correct_moniker != $url_id && count($_POST) == 0) {
                        header('HTTP/1.0 301 Moved Permanently');
                        $_new_url = build_url(array('page' => '_SELF', 'id' => $correct_moniker), '_SELF', NULL, true);
                        $new_url = $_new_url->evaluate();
                        header('Location: ' . $new_url);
                        exit;
                    }
                } else {
                    // See if it is deprecated
                    if (strpos(get_db_type(), 'mysql') !== false) {
                        $monikers = $GLOBALS['SITE_DB']->query_select('url_id_monikers USE INDEX (uim_moniker)', array('m_resource_id', 'm_deprecated'), array('m_resource_page' => get_page_name(), 'm_resource_type' => get_param('type', 'misc'), 'm_moniker' => $url_id));
                    } else {
                        $monikers = $GLOBALS['SITE_DB']->query_select('url_id_monikers', array('m_resource_id', 'm_deprecated'), array('m_resource_page' => get_page_name(), 'm_resource_type' => get_param('type', 'misc'), 'm_moniker' => $url_id));
                    }
                    if (!array_key_exists(0, $monikers)) {
                        warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
                    }
                    $deprecated = $monikers[0]['m_deprecated'] == 1;
                    if ($deprecated && count($_POST) == 0) {
                        $correct_moniker = find_id_moniker(array('page' => get_page_name(), 'type' => get_param('type', 'misc'), 'id' => $monikers[0]['m_resource_id']));
                        header('HTTP/1.0 301 Moved Permanently');
                        $_new_url = build_url(array('page' => '_SELF', 'id' => $correct_moniker), '_SELF', NULL, true);
                        $new_url = $_new_url->evaluate();
                        header('Location: ' . $new_url);
                        exit;
                    } else {
                        $_GET['id'] = $monikers[0]['m_resource_id'];
                        // We need to know the ID number rather than the moniker
                    }
                }
                break;
            }
        }
    }
    // Any messages to output?
    if (get_param_integer('redirected', 0) == 1) {
        $messages = $GLOBALS['SITE_DB']->query_select('messages_to_render', array('r_message', 'r_type'), array('r_session_id' => get_session_id()), 'ORDER BY r_time DESC');
        foreach ($messages as $message) {
            if ($GLOBALS['XSS_DETECT']) {
                ocp_mark_as_escaped($message['r_message']);
            }
            attach_message(protect_from_escaping($message['r_message']), $message['r_type']);
        }
        if (count($messages) != 0) {
            $GLOBALS['SITE_DB']->query('DELETE FROM ' . $GLOBALS['SITE_DB']->get_table_prefix() . 'messages_to_render WHERE r_session_id=' . strval((int) get_session_id()) . ' OR r_time<' . strval(time() - 60 * 60));
        }
    }
    if (in_safe_mode()) {
        $disable_safe_mode_url = get_self_url(true, true, array('keep_safe_mode' => NULL));
        attach_message(do_lang_tempcode('CURRENTLY_HAS_KEEP_SAFE_MODE', escape_html($disable_safe_mode_url)), 'notice');
    }
    if (get_param_integer('keep_fatalistic', 0) == 1) {
        $disable_fatalistic_url = get_self_url(true, true, array('keep_fatalistic' => NULL));
        attach_message(do_lang_tempcode('CURRENTLY_HAS_KEEP_FATALISTIC', escape_html($disable_fatalistic_url)), 'notice');
    }
    $special_page_type = get_param('special_page_type', 'view');
    global $ZONE;
    $keep_markers = get_param_integer('keep_markers', 0);
    $show_edit_links = get_param_integer('show_edit_links', 0);
    global $KEEP_MARKERS, $SHOW_EDIT_LINKS;
    $KEEP_MARKERS = $keep_markers == 1 || $special_page_type == 'show_markers';
    if ($KEEP_MARKERS && !headers_sent()) {
        header('Content-type: text/html; charset=' . get_charset());
    }
    $SHOW_EDIT_LINKS = $show_edit_links == 1 || $special_page_type == 'show_edit_links';
    $out_evaluated = NULL;
    if ($special_page_type != 'view' && $special_page_type != 'show_markers') {
        require_code('view_modes');
        initialise_special_page_types($special_page_type);
    }
    // Set up Xdebug profiling
    if ($special_page_type == 'profile') {
        if (function_exists('xdebug_start_profiling')) {
            xdebug_start_profiling();
        }
        // xdebug 1 style
        if (ini_get('xdebug.profiler_enable') != '1') {
            attach_message(escape_html('Profiling must be enabled in php.ini'), 'warn');
        }
        // xdebug 2 style
        if (!is_writable_wrap(ini_get('xdebug.profiler_output_dir'))) {
            attach_message(escape_html('xdebug.profiler_output_dir needs setting to a writable directory'), 'warn');
        }
    }
    // Allow the site to be closed
    $site_closed = get_option('site_closed');
    if ($site_closed == '1' && !has_specific_permission(get_member(), 'access_closed_site') && !$GLOBALS['IS_ACTUALLY_ADMIN']) {
        require_code('site2');
        closed_site();
    }
    // Work out which page we're viewing
    global $PAGE;
    $PAGE = get_page_name();
    $doing_special_page_type = $special_page_type != 'view' && $special_page_type != 'show_markers' && $special_page_type != 'show_edit_links' && $special_page_type != 'memory' && (has_specific_permission(get_member(), 'view_profiling_modes') || $GLOBALS['IS_ACTUALLY_ADMIN']);
    // Load up our frames into strings. Note that the header and the footer are fixed already.
    $middle = request_page($PAGE, true);
    global $CYCLES;
    $CYCLES = array();
    // Here we reset some Tempcode environmental stuff, because template compilation or preprocessing may have dirtied things
    if ($middle === NULL || $middle->is_definitely_empty()) {
        $GLOBALS['HTTP_STATUS_CODE'] = '404';
        if (!headers_sent()) {
            if (!browser_matches('ie') && strpos(ocp_srv('SERVER_SOFTWARE'), 'IIS') === false) {
                header('HTTP/1.0 404 Not Found');
            }
        }
        $title = get_page_title('ERROR_OCCURRED');
        $text = do_lang_tempcode('NO_PAGE_OUTPUT');
        $middle = warn_screen($title, $text, false);
    }
    // Extra stuff we can tag on (like messages)
    $additional = new ocp_tempcode();
    $site_closed = get_option('site_closed');
    // May have been JUST changed in page load - think Setup Wizard
    if ($site_closed == '1' && $PAGE != 'login' && $PAGE != 'join' && get_param_integer('wide_high', 0) == 0) {
        $additional->attach(do_template('ADDITIONAL', array('_GUID' => '03a41a91606b3ad05330e7d6f3e741c1', 'TYPE' => 'notice', 'MESSAGE' => do_lang_tempcode(has_specific_permission(get_member(), 'access_closed_site') ? 'SITE_SPECIAL_ACCESS' : 'SITE_SPECIAL_ACCESS_SU'))));
    }
    if ($GLOBALS['IS_ACTUALLY_ADMIN']) {
        $unsu_link = get_self_url(true, true, array('keep_su' => NULL));
        $su_username = $GLOBALS['FORUM_DRIVER']->get_username(get_member());
        $additional->attach(do_template('ADDITIONAL', array('_GUID' => '13a41a91606b3ad05330e7d6f3e741c1', 'TYPE' => 'notice', 'MESSAGE' => do_lang_tempcode('USING_SU', escape_html($unsu_link), escape_html($su_username)))));
    }
    $out = new ocp_tempcode();
    // This is important - it makes sure the tempcode tree appears nicely
    $middle->handle_symbol_preprocessing();
    // Due to the '->evaluate()' below, plus so that some symbol preprocessing can be passed into header
    $out->attach(do_header());
    if (function_exists('memory_get_usage') && get_param('special_page_type', '') == 'memory') {
        if (function_exists('memory_get_peak_usage')) {
            $memory_usage = memory_get_peak_usage();
        } else {
            $memory_usage = memory_get_usage();
        }
        $additional->attach(do_template('ADDITIONAL', array('_GUID' => 'd605c0d111742a8cd2d4ef270a1e5fe1', 'TYPE' => 'inform', 'MESSAGE' => do_lang_tempcode('MEMORY_USAGE', float_format(round(floatval($memory_usage) / 1024.0 / 1024.0, 2))))));
    }
    // Whack it into our global template
    global $ATTACHED_MESSAGES;
    $global_template = 'GLOBAL';
    if (get_option('show_docs') == '0') {
        $GLOBALS['HELPER_PANEL_TUTORIAL'] = '';
    }
    $helper_panel_pic = $GLOBALS['HELPER_PANEL_PIC'];
    if ($helper_panel_pic != '') {
        if (find_theme_image($helper_panel_pic, true) == '') {
            $helper_panel_pic = '';
        }
    }
    $global = do_template($global_template, array('HELPER_PANEL_TUTORIAL' => $GLOBALS['HELPER_PANEL_TUTORIAL'], 'HELPER_PANEL_HTML' => $GLOBALS['HELPER_PANEL_HTML'], 'HELPER_PANEL_TEXT' => $GLOBALS['HELPER_PANEL_TEXT'], 'HELPER_PANEL_PIC' => $helper_panel_pic, 'MIDDLE' => $doing_special_page_type ? $middle : $middle->evaluate(), 'MESSAGE_TOP' => $ATTACHED_MESSAGES, 'MESSAGE' => $additional, 'BREADCRUMBS' => breadcrumbs()));
    unset($middle);
    $out->attach($global);
    $out->attach(do_footer());
    $out->handle_symbol_preprocessing();
    if (get_value('xhtml_strict') === '1') {
        $out = make_xhtml_strict($out);
    }
    // Validation
    $novalidate = get_param_integer('keep_novalidate', get_param_integer('novalidate', 0));
    $show_edit_links = get_param_integer('show_edit_links', 0);
    if ((in_array(ocp_srv('HTTP_HOST'), array('localhost', 'test.ocportal.com')) || $GLOBALS['FORUM_DRIVER']->is_staff(get_member())) && ($special_page_type == 'code' || $novalidate == 0 && get_option('validation') == '1') && $GLOBALS['REFRESH_URL'][0] == '' && $show_edit_links == 0) {
        require_code('view_modes');
        $out_evaluated = $out->evaluate(NULL, false);
        do_xhtml_validation($out_evaluated, $special_page_type == 'code' && get_param_integer('preview_mode', NULL) === NULL, get_param_integer('preview_mode', 0));
    }
    // Cacheing for spiders
    if (running_script('index') && count($_POST) == 0 && isset($GLOBALS['SITE_INFO']['fast_spider_cache']) && $GLOBALS['SITE_INFO']['fast_spider_cache'] == '1' && is_guest()) {
        $bot_type = get_bot_type();
        if (($bot_type !== NULL || isset($GLOBALS['SITE_INFO']['any_guest_cached_too']) && $GLOBALS['SITE_INFO']['any_guest_cached_too'] == '1') && can_fast_spider_cache()) {
            $fast_cache_path = get_custom_file_base() . '/persistant_cache/' . md5(serialize(get_self_url_easy()));
            if ($bot_type === NULL) {
                $fast_cache_path .= '__non-bot';
            }
            if (!array_key_exists('js_on', $_COOKIE)) {
                $fast_cache_path .= '__no-js';
            }
            if (is_mobile()) {
                $fast_cache_path .= '_mobile';
            }
            $fast_cache_path .= '.gcd';
            if (!is_dir(get_custom_file_base() . '/persistant_cache/')) {
                if (@mkdir(get_custom_file_base() . '/persistant_cache/', 0777)) {
                    fix_permissions(get_custom_file_base() . '/persistant_cache/', 0777);
                    sync_file(get_custom_file_base() . '/persistant_cache/');
                } else {
                    intelligent_write_error($fast_cache_path);
                }
            }
            $out_evaluated = $out->evaluate(NULL, false);
            $myfile = @fopen($fast_cache_path, 'wb') or intelligent_write_error($fast_cache_path);
            if (function_exists('gzencode')) {
                fwrite($myfile, gzencode($out_evaluated, 9));
            } else {
                fwrite($myfile, $out_evaluated);
            }
            fclose($myfile);
            fix_permissions($fast_cache_path);
            sync_file($fast_cache_path);
        }
    }
    if ($doing_special_page_type) {
        special_page_types($special_page_type, $out, $out_evaluated);
    }
    // We calculated the time before outputting so that latency and bandwidth do not adversely affect the result
    global $PAGE_START_TIME, $PAGE_STRING;
    $page_generation_time = microtime_diff($PAGE_START_TIME, microtime(false));
    if (!$GLOBALS['QUICK_REDIRECT']) {
        if ($out_evaluated !== NULL) {
            echo $out_evaluated;
        } else {
            $GLOBALS['FINISHING_OUTPUT'] = true;
            $out->evaluate_echo();
        }
    }
    // Finally, stats
    if ($PAGE_STRING !== NULL) {
        log_stats($PAGE_STRING, intval($page_generation_time));
    }
    // When someone hits the Admin Zone front page.
    if ($ZONE['zone_name'] == 'adminzone' && get_page_name() == 'start') {
        // Security feature admins can turn on
        require_code('notifications');
        $current_username = $GLOBALS['FORUM_DRIVER']->get_username(get_member());
        $subject = do_lang('AFA_NOTIFICATION_MAIL_SUBJECT', $current_username, get_site_name(), get_ip_address());
        $mail = do_lang('AFA_NOTIFICATION_MAIL', comcode_escape(get_site_name()), comcode_escape($current_username), comcode_escape(get_ip_address()));
        dispatch_notification('adminzone_frontpage_accessed', NULL, $subject, $mail);
        // Track very basic details of what sites use ocPortal. You can remove if you like.
        if (preg_match('#^localhost[\\.\\:$]?#', ocp_srv('HTTP_HOST')) == 0) {
            global $EXPIRE, $KEY;
            $timeout_before = @ini_get('default_socket_timeout');
            @ini_set('default_socket_timeout', '3');
            http_download_file('http://ocportal.com/user.php?url=' . urlencode(get_base_url()) . '&name=' . urlencode(get_site_name()) . '&registered=2&key=' . ($KEY === NULL ? '' : strval($KEY)) . '&expire=' . ($EXPIRE === NULL ? '' : strval($EXPIRE)) . '&version=' . urlencode(ocp_version_full()), NULL, false);
            @ini_set('default_socket_timeout', $timeout_before);
        }
    }
    // Little disk space check
    $last_space_check = get_value('last_space_check');
    if ($last_space_check === NULL || intval($last_space_check) < time() - 60 * 60 * 3) {
        set_value('last_space_check', strval(time()));
        $low_space_check = intval(get_option('low_space_check')) * 1024 * 1024;
        $disk_space = @disk_free_space(get_file_base());
        if (is_integer($disk_space) && $disk_space < $low_space_check) {
            require_code('notifications');
            $subject = do_lang('LOW_DISK_SPACE_SUBJECT', NULL, NULL, NULL, get_site_default_lang());
            $message = do_lang('LOW_DISK_SPACE_MAIL', strval(intval(round($disk_space / 1024 / 1024))), NULL, NULL, get_site_default_lang());
            dispatch_notification('low_disk_space', NULL, $subject, $message, NULL, A_FROM_SYSTEM_PRIVILEGED);
        }
    }
    //exit();
}
Beispiel #22
0
/**
 * Get an image
 *
 * @return tempcode		Place holder text.
 */
function placeholder_image()
{
    $text = '<img src="http://ocportal.com/themes/ocproducts/images/newlogo.gif" title="test" alt="test" />';
    if (function_exists('ocp_mark_as_escaped')) {
        ocp_mark_as_escaped($text);
    }
    return make_string_tempcode($text);
}
Beispiel #23
0
 /**
  * This function is a very basic query executor. It shouldn't usually be used by you, as there are abstracted versions available.
  *
  * @param  string			The complete SQL query
  * @param  array			A DB connection
  * @param  ?integer		The maximum number of rows to affect (NULL: no limit)
  * @param  ?integer		The start row to affect (NULL: no specification)
  * @param  boolean		Whether to output an error on failure
  * @param  boolean		Whether to get the autoincrement ID created for an insert query
  * @return ?mixed			The results (NULL: no results), or the insert ID
  */
 function db_query($query, $db, $max = NULL, $start = NULL, $fail_ok = false, $get_insert_id = false)
 {
     if (substr($query, 0, 7) == 'SELECT') {
         if (!is_null($max) && !is_null($start)) {
             $query .= ' LIMIT ' . strval(intval($start)) . ',' . strval(intval($max));
         } elseif (!is_null($max)) {
             $query .= ' LIMIT ' . strval(intval($max));
         } elseif (!is_null($start)) {
             $query .= ' LIMIT ' . strval(intval($start)) . ',30000000';
         }
     }
     $results = @sqlite_query($db, $query);
     if (($results === false || strtoupper(substr($query, 0, 7)) == 'SELECT ' && $results === true) && !$fail_ok) {
         $err = sqlite_last_error($db);
         if (function_exists('ocp_mark_as_escaped')) {
             ocp_mark_as_escaped($err);
         }
         if (!running_script('upgrader') && get_page_name() != 'admin_import') {
             if (!function_exists('do_lang') || is_null(do_lang('QUERY_FAILED', NULL, NULL, NULL, NULL, false))) {
                 fatal_exit(htmlentities('Query failed: ' . $query . ' : ' . $err));
             }
             fatal_exit(do_lang_tempcode('QUERY_FAILED', escape_html($query), $err));
         } else {
             echo htmlentities('Database query failed: ' . $query . ' [') . $err . htmlentities(']' . '<br />' . chr(10));
             return NULL;
         }
     }
     if (strtoupper(substr($query, 0, 7)) == 'SELECT ' && $results !== false && $results !== true) {
         return $this->db_get_query_rows($results);
     }
     if ($get_insert_id) {
         if (strtoupper(substr($query, 0, 7)) == 'UPDATE ') {
             return NULL;
         }
         return sqlite_last_insert_rowid($db);
     }
     return NULL;
 }
/**
 * Get an emoticon chooser template.
 *
 * @param  object			Link to the real forum driver
 * @param  string			The ID of the form field the emoticon chooser adds to
 * @return tempcode		The emoticon chooser template
 */
function _helper_get_emoticon_chooser($this_ref, $field_name)
{
    $extra = has_specific_permission(get_member(), 'use_special_emoticons') ? '' : ' AND e_is_special=0';
    $emoticons = $this_ref->connection->query('SELECT * FROM ' . $this_ref->connection->get_table_prefix() . 'f_emoticons WHERE e_relevance_level=0' . $extra);
    $em = new ocp_tempcode();
    foreach ($emoticons as $emo) {
        $code = $emo['e_code'];
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($code);
        }
        $em->attach(do_template('EMOTICON_CLICK_CODE', array('_GUID' => '1a75f914e09f2325ad96ad679bcffe88', 'FIELD_NAME' => $field_name, 'CODE' => $code, 'IMAGE' => apply_emoticons($code))));
    }
    return $em;
}
Beispiel #25
0
/**
 * XML escape the input string.
 *
 * @param  string			Input string
 * @param  integer		Quote style
 * @return string			Escaped version of input string
 */
function xmlentities($string, $quote_style = ENT_COMPAT)
{
    $ret = str_replace('>', '&gt;', str_replace('<', '&lt;', str_replace('"', '&quot;', str_replace('&', '&amp;', $string))));
    if (function_exists('ocp_mark_as_escaped')) {
        ocp_mark_as_escaped($ret);
    }
    return $ret;
}
Beispiel #26
0
/**
 * XHTML-aware substring extraction. Note that it will strip images, linebreaks, rules, etc - it's intended really for inline XHTML.
 *
 * @param  string			The text to perform on.
 * @param  integer		The start position of the cut (HTML tags will be taken from before this though).
 * @param  ?integer		The length you want the concatenated text to be (NULL: go to end).
 * @param  boolean		Whether to do a substr based on literal position in XHTML, rather than based on number of visible characters.
 * @param  boolean		Whether to add ellipses.
 * @param  float			A fraction of the length we may exceed by in order to maintain grammar tolerance (finish sentences, finish paragraphs, finish the whole thing).
 * @return string			The result.
 */
function xhtml_substr($html, $from, $length = NULL, $literal_pos = false, $ellipses = false, $grammar_completeness_tolerance = 0.0)
{
    /* TESTS
    	$out='';
    	$out.=xhtml_substr('test',0,NULL).chr(10); //=test
    	$out.=xhtml_substr('test',0,4).chr(10); //=test
    	$out.=xhtml_substr('test',0,3).chr(10); //=tes
    	$out.=xhtml_substr('test',1,3).chr(10); //=est
    	$out.=xhtml_substr('test',1,2).chr(10); //=es
    	$out.=xhtml_substr('test',-3).chr(10); //=est
    	$out.=xhtml_substr('test',-2).chr(10); //=st
    	$out.=xhtml_substr('<i>test</i>',0,NULL).chr(10); //=<i>test</i>
    	$out.=xhtml_substr('<i>test</i>',0,4).chr(10); //=<i>test</i>
    	$out.=xhtml_substr('<i>test</i>',0,3).chr(10); //=<i>tes</i>
    	$out.=xhtml_substr('<i>test</i>',1,3).chr(10); //=<i>est</i>
    	$out.=xhtml_substr('<i>test</i>',1,2).chr(10); //=<i>es</i>
    	$out.=xhtml_substr('<i>test</i>',-3).chr(10); //=<i>est</i>
    	$out.=xhtml_substr('<i>test</i>',-2).chr(10); //=<i>st</i>
    	$out.=xhtml_substr('<a><br /><x><i foo="bar">test</i>',-2).chr(10); //=<a><x><i foo="bar">st</i></x></a>
    */
    $html = preg_replace('#<\\!--.*($|-->)#Us', '', $html);
    // Strip comments
    // Sort out the negative offset possibility
    if ($from < 0) {
        $from = strlen(strip_tags($html)) + $from;
        // Not perfectly accurate using strip_tags as it's a different algorithm - but close enough, considering all our XHTML is well formed anyway
    }
    $tag_stack = array();
    // A stack of simple tags (opening only, just the names), that we can search
    $current_tag = '';
    $in_tag = false;
    $in_entity = false;
    $in_tag_type = '';
    $real_from = 0;
    $_html_buildup = '';
    $html_buildup = array();
    // A stack of HTML tags we need from before we start our portion, to move us into the right tag context. None tags are thrown out.
    // Reset the character counter and pass through (part of) the entire text
    $c = 0;
    $total_length = strlen($html);
    $total_length_minus_one = $total_length - 1;
    $end_pos = is_null($length) ? $total_length : $from + $length;
    for ($i = 0; $i < $total_length; $i++) {
        // Load the current character and the next one if the string has not arrived at the last character
        $current_char = $html[$i];
        $next_char = $i < $total_length - 1 ? $html[$i + 1] : '';
        if ($in_entity) {
            if ($current_char == ';') {
                $in_entity = false;
            } else {
                if (preg_match('#[\\#\\w]#', $current_char) == 0) {
                    $in_entity = false;
                    $_html_buildup = preg_replace('#(.*)&#s', '${1}&amp;', $_html_buildup);
                    $i--;
                    continue;
                }
            }
            if (($literal_pos ? $i : $c) < $from || $real_from == 0 && $from != 0) {
                $_html_buildup .= $current_char;
            }
        } elseif ($in_tag) {
            if ($current_char == '/' && ($next_char == '>' || $current_tag == '')) {
                if ($current_tag == '') {
                    $in_tag_type = 'CLOSE';
                } else {
                    $in_tag_type = 'SELF_CLOSE';
                }
            } elseif ($current_char == '>') {
                $in_tag = false;
                if ($in_tag_type == 'OPEN' || $in_tag_type == '') {
                    if ($current_tag != '!--') {
                        if ($grammar_completeness_tolerance != 0.0 && _smart_grammar_says_futile($end_pos, $grammar_completeness_tolerance, $i + 1, $html, $length)) {
                            // Force termination
                            $length = 0;
                            $end_pos = 0;
                        }
                        if ($current_tag != 'br' && $current_tag != 'img' && $current_tag != 'hr') {
                            // A little sanity checking, for HTML used as XHTML
                            $tag_stack[] = $current_tag;
                        }
                    }
                } elseif ($in_tag_type == 'CLOSE') {
                    if (@$tag_stack[count($tag_stack) - 1] == $current_tag) {
                        array_pop($tag_stack);
                    } else {
                        $reverse_tag_stack = array_reverse($tag_stack);
                        foreach ($reverse_tag_stack as $rti => $rtt) {
                            if ($rtt == $current_tag) {
                                unset($reverse_tag_stack[$rti]);
                                $tag_stack = array_reverse($reverse_tag_stack);
                                break;
                            }
                        }
                    }
                } elseif ($in_tag_type == 'SELF_CLOSE') {
                    if ($grammar_completeness_tolerance != 0.0 && _smart_grammar_says_futile($end_pos, $grammar_completeness_tolerance, $i + 1, $html, $length)) {
                        // Force termination
                        $length = 0;
                        $end_pos = 0;
                    }
                }
            } elseif (trim($current_char) == '') {
                $in_tag_type = 'OPEN';
            } elseif ($in_tag_type == '' || $in_tag_type == 'CLOSE') {
                $current_tag .= $current_char;
            }
            if (($literal_pos ? $i : $c) < $from || $real_from == 0 && $from != 0) {
                $_html_buildup .= $current_char;
                if (!$in_tag) {
                    if ($in_tag_type == 'CLOSE' && @$html_buildup[count($html_buildup) - 1][0] == $current_tag) {
                        array_pop($html_buildup);
                    } elseif ($in_tag_type != 'SELF_CLOSE') {
                        $html_buildup[] = array($current_tag, $_html_buildup);
                    }
                }
            }
        } else {
            if ($current_char == '&') {
                $in_entity = true;
                $_html_buildup = '';
                if (($literal_pos ? $i : $c) < $from || $real_from == 0 && $from != 0) {
                    $_html_buildup .= $current_char;
                }
                $c++;
            } elseif ($current_char == '<' && $next_char == '!' && substr($html, $i, 9) == '<![CDATA[') {
                $close = strpos($html, '//]]>', $i);
                if ($close !== false) {
                    $i = $close + 4;
                } else {
                    $i = $total_length;
                }
            } elseif ($current_char == '<') {
                $in_tag = true;
                $in_tag_type = '';
                $current_tag = '';
                $_html_buildup = '';
                if (($literal_pos ? $i : $c) < $from || $real_from == 0 && $from != 0) {
                    $_html_buildup .= $current_char;
                }
            } else {
                if ($real_from == 0) {
                    if ($literal_pos) {
                        // Optimisation: jump forwards as far as non-interesting
                        $jump_max_a = strpos($html, '<', $i);
                        if ($jump_max_a === false) {
                            $jump_max_a = $from;
                        } else {
                            $jump_max_a--;
                        }
                        $jump_max_b = strpos($html, '&', $i);
                        if ($jump_max_b === false) {
                            $jump_max_b = $from;
                        } else {
                            $jump_max_b--;
                        }
                        $jump_max_c = $from;
                        $min = min($jump_max_a, $jump_max_b, $jump_max_c);
                        $dif = $min - $i;
                        if ($dif > 0) {
                            $i = $min;
                            $c += $dif;
                        }
                    }
                    // We've not reached our length yet but we have JUST reached a usable from. Set real_from  (by doing it here we make sure we don't crop from inside an entity or tag)
                    if (($literal_pos ? $i : $c) >= $from && $from != 0) {
                        $real_from = $i;
                    }
                }
                $c++;
            }
        }
        // Check if the counter has reached the minimum length yet, then wait for the tag_counter to become 0, and chop the string there
        $ord = ord($current_char);
        if (!$in_tag && !$in_entity && !($ord >= 192 && $ord <= 223) && ($literal_pos ? $i : $c) >= $end_pos && ($grammar_completeness_tolerance == 0.0 || !_smart_grammar_says_continue($end_pos, $grammar_completeness_tolerance, $i, $html, $length)) || $i == $total_length_minus_one) {
            $entity = '&hellip;';
            if (function_exists('ocp_mark_as_escaped')) {
                ocp_mark_as_escaped($entity);
            }
            if ($real_from == 0 && $from != 0) {
                $html_buildup = array();
            }
            $new_html = '';
            if ($ellipses) {
                $start_ellipses = $from > 0 ? $entity : '';
            } else {
                $start_ellipses = '';
            }
            if ($ellipses) {
                $end_ellipses = !is_null($length) && $end_pos < $total_length - 1 ? $entity : '';
            } else {
                $end_ellipses = '';
            }
            $no_text_inside = array('tr', 'thead', 'colgroup', 'table', 'ul', 'ol', 'dl', 'dir', 'menu', 'applet', 'param', 'embed', 'object', 'legend', 'select', 'tfoot', 'ruby');
            if (in_array(array_peek($tag_stack), $no_text_inside)) {
                $new_html = rtrim($new_html) . $start_ellipses;
                $start_ellipses = '';
            }
            foreach ($html_buildup as $details) {
                $new_html .= $details[1];
            }
            $new_html = rtrim($new_html) . $start_ellipses;
            $main_portion = substr($html, $real_from, $i - $real_from + 1);
            $new_html .= $main_portion;
            if (!in_array(array_peek($tag_stack), $no_text_inside)) {
                $new_html = rtrim($new_html) . $end_ellipses;
                $end_ellipses = '';
            }
            foreach (array_reverse($tag_stack) as $tag) {
                $new_html .= '</' . $tag . '>';
            }
            // Shall we back-track a bit to stop cutting up a word?
            $backtrack = strrpos($new_html, ' ');
            $backtrack_safety = strrpos($new_html, '>');
            if ($current_char != ' ' && $grammar_completeness_tolerance != 0.0 && $backtrack !== false && floatval(strlen($new_html) - $backtrack) < $grammar_completeness_tolerance * strlen($new_html) && ($backtrack_safety === false || $backtrack > $backtrack_safety)) {
                $new_html = substr($new_html, 0, $backtrack);
            }
            $new_html = rtrim($new_html) . $end_ellipses;
            $new_html = preg_replace('#<!--.*(-->|$)#Us', '', $new_html);
            // Our algorithm doesn't handle comments so we need to be slightly clever about it
            $new_html = preg_replace('#<script.*</script>#Us', '', $new_html);
            // ... and also script/CDATA stuff, due to problems in XHTML/HTML incompatibility bypass techniques that use character data (which we skip)
            // Remove some empty tags that shouldn't be empty (e.g. td)
            $may_not_be_empty = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'blockquote', 'pre', 'br', 'hr', 'fieldset', 'address', 'noscript', 'table', 'tbody', 'tfoot', 'thead', 'tr', 'dd', 'dt', 'dl', 'li', 'ol', 'ul', 'rbc', 'rtc', 'rb', 'rt', 'rp', 'span', 'abbr', 'acronym', 'cite', 'code', 'dfn', 'em', 'strong', 'kbd', 'q', 'samp', 'var', 'sub', 'sup', 'tt', 'del', 'ruby', 'bdo', 'img', 'ins', 'param', 'input', 'select', 'object', 'caption', 'label', 'b', 'i', 'small', 'big', 'base', 'body', 'col', 'colgroup', 'map', 'optgroup', 'option', 'legend', 'area', 'form');
            foreach ($may_not_be_empty as $t) {
                $new_html = preg_replace('#<' . $t . '>\\s*</' . $t . '>#', '', $new_html);
            }
            if ($ellipses) {
                $new_html = str_replace(array('</p>' . $entity, '</div>' . $entity), array($entity . '</p>', $entity . '</div>'), $new_html);
            }
            return $new_html;
        }
    }
    return $html;
    // Should never get here
}
Beispiel #27
0
    /**
     * Standard modular run function. Creates custom graphics from parameters.
     *
     * @param  array		Map of hook parameters (relayed from block parameters map).
     * @param  object		The block itself (contains utility methods).
     * @return tempcode	HTML to output.
     */
    function run($map, &$Block)
    {
        require_css('sifr');
        require_javascript('javascript_sifr');
        $tag = array_key_exists('tag', $map) ? $map['tag'] : 'h2';
        if (!array_key_exists('data', $map)) {
            $map['data'] = do_lang('FILL_IN_DATA_PARAM');
        }
        $id = 'sifr' . uniqid('');
        $font = array_key_exists('font', $map) ? $map['font'] : 'tradegothic';
        if (substr($font, -4) == '.swf') {
            $font = substr($font, 0, strlen($font) - 4);
        }
        if (file_exists(get_file_base() . '/data_custom/sifr/' . $font . '.swf')) {
            $font = get_base_url() . '/data_custom/sifr/' . $font . '.swf';
        } else {
            $font = get_base_url() . '/data/sifr/' . $font . '.swf';
        }
        $extra = '';
        if (!array_key_exists('color', $map)) {
            $map['color'] = '#000000';
        }
        $extra .= ', sColor:"' . php_addslashes($map['color']) . '"';
        if (array_key_exists('link_color', $map)) {
            $extra .= ', sBgColor:"' . php_addslashes($map['link_color']) . '"';
        }
        if (array_key_exists('hover_color', $map)) {
            $extra .= ', sHoverColor:"' . php_addslashes($map['hover_color']) . '"';
        }
        if (array_key_exists('padding_top', $map)) {
            $extra .= ', nPaddingTop:"' . php_addslashes($map['padding_top']) . '"';
        }
        if (array_key_exists('padding_bottom', $map)) {
            $extra .= ', nPaddingBottom:"' . php_addslashes($map['padding_bottom']) . '"';
        }
        if (array_key_exists('padding_left', $map)) {
            $extra .= ', nPaddingLeft:"' . php_addslashes($map['padding_left']) . '"';
        }
        if (array_key_exists('padding_right', $map)) {
            $extra .= ', nPaddingRight:"' . php_addslashes($map['padding_right']) . '"';
        }
        if (array_key_exists('flash_vars', $map)) {
            $extra .= ', sFlashVars:"' . php_addslashes($map['flash_vars']) . '"';
        }
        if (array_key_exists('case', $map)) {
            $extra .= ', sCase:"' . php_addslashes($map['case']) . '"';
        }
        if (!array_key_exists('wmode', $map)) {
            $map['wmode'] = 'transparent';
        }
        $extra .= ', sWmode:"' . php_addslashes($map['wmode']) . '"';
        $ret = '<' . $tag . ' id="' . escape_html($id) . '">' . $map['data'] . '</' . $tag . '>';
        $ret .= '
			<script type="text/javascript">//<![CDATA[
			if (typeof sIFR=="function")
				sIFR.replaceElement(named({sSelector:"#' . php_addslashes($id) . '", sFlashSrc:"' . php_addslashes($font) . '"' . $extra . '}));
			//]]></script>';
        if (function_exists('ocp_mark_as_escaped')) {
            ocp_mark_as_escaped($ret);
        }
        return make_string_tempcode($ret);
    }
Beispiel #28
0
 /**
  * Standard modular run function.
  *
  * @param  array		A map of parameters.
  * @return tempcode	The result of execution.
  */
 function run($map)
 {
     require_all_lang();
     require_code('zones2');
     $skip_pages = array_key_exists('skip', $map) ? explode(',', $map['skip']) : array();
     $comcode_page_rows = $GLOBALS['SITE_DB']->query_select('comcode_pages', array('*'));
     $_zones = array();
     $zones = find_all_zones(false, true);
     $GLOBALS['MEMORY_OVER_SPEED'] = true;
     $low_memory = ini_get('memory_limit') != '-1' && ini_get('memory_limit') != '0' && ini_get('memory_limit') != '' && intval(preg_replace('#M$#', '', ini_get('memory_limit'))) < 26 || get_option('has_low_memory_limit') === '1';
     // Reorder a bit
     $zones2 = array();
     foreach (array('', 'site') as $zone_match) {
         foreach ($zones as $i => $zone) {
             if ($zone[0] == $zone_match) {
                 $zones2[] = $zone;
                 unset($zones[$i]);
             }
         }
     }
     $zones2 = array_merge($zones2, $zones);
     foreach ($zones2 as $z) {
         list($zone, $zone_title, , $zone_default_page) = $z;
         if (has_zone_access(get_member(), $zone)) {
             $_pages = array();
             $pages = find_all_pages_wrap($zone);
             if (isset($pages[$zone_default_page])) {
                 $default = $pages[$zone_default_page];
                 $pages = array($zone_default_page => $default) + $pages;
             }
             foreach ($pages as $page => $page_type) {
                 if (is_integer($page)) {
                     $page = strval($page);
                 }
                 if (substr($page, 0, 6) == 'panel_') {
                     continue;
                 }
                 if (substr($page, 0, 1) == '_') {
                     continue;
                 }
                 if (in_array($page, $skip_pages)) {
                     continue;
                 }
                 if (in_array($zone . ':' . $page, $skip_pages)) {
                     continue;
                 }
                 if ($page == '404') {
                     continue;
                 }
                 if (strpos($page, '_tree_made') !== false) {
                     continue;
                 }
                 if ($page == 'sitemap') {
                     continue;
                 }
                 if ($page == 'forums' && substr($page_type, 0, 7) == 'modules' && (get_forum_type() == 'ocf' || get_forum_type() == 'none')) {
                     continue;
                 }
                 if ($page == 'join' && substr($page_type, 0, 7) == 'modules' && !is_guest()) {
                     continue;
                 }
                 if (has_page_access(get_member(), $page, $zone)) {
                     $_entrypoints = array();
                     $__entrypoints = $low_memory ? array(NULL) : extract_module_functions_page($zone, $page, array('get_entry_points'));
                     if (!is_null($__entrypoints[0])) {
                         $entrypoints = is_array($__entrypoints[0]) ? call_user_func_array($__entrypoints[0][0], $__entrypoints[0][1]) : (strpos($__entrypoints[0], '::') !== false ? NULL : eval($__entrypoints[0]));
                         // The strpos thing is a little hack that allows it to work for base-class derived modules
                         if (is_null($entrypoints)) {
                             $path = zone_black_magic_filterer($zone . ($zone == '' ? '' : '/') . 'pages/' . $page_type . '/' . $page . '.php', true);
                             if ($low_memory && !defined('HIPHOP_PHP') && strpos(file_get_contents(get_file_base() . '/' . $path), ' extends standard_aed_module') !== false) {
                                 $new_code = str_replace(',parent::get_entry_points()', '', str_replace('parent::get_entry_points(),', '', $__entrypoints[0]));
                                 if (strpos($new_code, 'parent::') !== false) {
                                     continue;
                                 }
                                 $entrypoints = eval($new_code);
                             } else {
                                 require_code($path);
                                 if (class_exists('Mx_' . filter_naughty_harsh($page))) {
                                     $object = object_factory('Mx_' . filter_naughty_harsh($page));
                                 } else {
                                     $object = object_factory('Module_' . filter_naughty_harsh($page));
                                 }
                                 $entrypoints = $object->get_entry_points();
                             }
                         }
                     } else {
                         $entrypoints = array('!');
                     }
                     if (!is_array($entrypoints)) {
                         $entrypoints = array('!');
                     }
                     if ($entrypoints == array('!')) {
                         $url = build_url(array('page' => $page), $zone, NULL, false, false, true);
                         $title = ucwords(str_replace('_', ' ', $page));
                         if (substr($page_type, 0, 7) == 'comcode') {
                             foreach ($comcode_page_rows as $page_row) {
                                 if ($page_row['p_validated'] == 0 && $page_row['the_page'] == $page && $page_row['the_zone'] == $zone) {
                                     continue 2;
                                 }
                             }
                             $path = zone_black_magic_filterer((strpos($page_type, '_custom') !== false ? get_custom_file_base() : get_file_base()) . '/' . filter_naughty($zone) . '/pages/' . filter_naughty($page_type) . '/' . $page . '.txt');
                             if (!is_file($path)) {
                                 $path = zone_black_magic_filterer(get_file_base() . '/' . filter_naughty($zone) . '/pages/' . filter_naughty($page_type) . '/' . $page . '.txt');
                             }
                             $page_contents = file_get_contents($path);
                             $matches = array();
                             if (preg_match('#\\[title[^\\]]*\\]#', $page_contents, $matches) != 0) {
                                 $start = strpos($page_contents, $matches[0]) + strlen($matches[0]);
                                 $end = strpos($page_contents, '[/title]', $start);
                                 $matches = array();
                                 $title_portion = str_replace('{$SITE_NAME}', get_site_name(), substr($page_contents, $start, $end - $start));
                                 if (preg_match('#\\{\\!([\\w:]+)\\}#', $title_portion, $matches) != 0) {
                                     $title_portion = str_replace($matches[0], do_lang($matches[1]), $title_portion);
                                 }
                                 if (preg_match('#^[^<>\\[\\{\\&]*$#', $title_portion, $matches) != 0) {
                                     $title = $matches[0];
                                 } elseif (!$low_memory) {
                                     $_title = comcode_to_tempcode($title_portion);
                                     $title = strip_tags(@html_entity_decode($_title->evaluate(), ENT_QUOTES, get_charset()));
                                 }
                             }
                         } elseif (substr($page_type, 0, 4) == 'html') {
                             $path = zone_black_magic_filterer((strpos($page_type, '_custom') !== false ? get_custom_file_base() : get_file_base()) . '/' . filter_naughty($zone) . '/pages/' . filter_naughty($page_type) . '/' . $page . '.htm');
                             $page_contents = file_get_contents($path);
                             $matches = array();
                             if (preg_match('#\\<title[^\\>]*\\>#', $page_contents, $matches) != 0) {
                                 $start = strpos($page_contents, $matches[0]) + strlen($matches[0]);
                                 $end = strpos($page_contents, '</title>', $start);
                                 $title = strip_tags(@html_entity_decode(substr($page_contents, $start, $end - $start), ENT_QUOTES, get_charset()));
                             }
                         }
                         $temp = do_template('BLOCK_MAIN_SITEMAP_NEST', array('_GUID' => '92e657f8b9a3642df053f54e724e66f6', 'URL' => $url, 'NAME' => $title, 'CHILDREN' => array()));
                         $_pages[$title] = $temp->evaluate();
                         // FUDGEFUDGE
                     } elseif (count($entrypoints) != 0) {
                         foreach ($entrypoints as $entrypoint => $title) {
                             if (($entrypoint == 'concede' || $entrypoint == 'invisible' || $entrypoint == 'logout') && is_guest()) {
                                 continue;
                             }
                             if ($entrypoint == '!') {
                                 $url = build_url(array('page' => $page), $zone, NULL, false, false, true);
                             } else {
                                 $url = build_url(array('page' => $page, 'type' => $entrypoint), $zone, NULL, false, false, true);
                             }
                             $_entrypoints[$title] = do_template('BLOCK_MAIN_SITEMAP_NEST', array('_GUID' => 'ae2ed2549644a8e699e0938b3ab98ddb', 'URL' => $url, 'NAME' => do_lang_tempcode($title), 'CHILDREN' => array()));
                         }
                         //ksort($_entrypoints);
                         $title = do_lang('MODULE_TRANS_NAME_' . $page, NULL, NULL, NULL, NULL, false);
                         if (is_null($title)) {
                             $title = ucwords(str_replace('_', ' ', preg_replace('#^ocf\\_#', '', preg_replace('#^' . str_replace('#', '\\#', preg_quote($zone)) . '_#', '', preg_replace('#^' . str_replace('#', '\\#', preg_quote(str_replace('zone', '', $zone))) . '_#', '', $page)))));
                         }
                         if (count($_entrypoints) == 1) {
                             $temp_keys = array_keys($_entrypoints);
                             $temp = $_entrypoints[$temp_keys[0]];
                         } else {
                             $temp = do_template('BLOCK_MAIN_SITEMAP_NEST', array('_GUID' => 'dfc5cc7db0301acd938d3b2e3fceaab8', 'URL' => new ocp_tempcode(), 'NAME' => $title, 'CHILDREN' => $_entrypoints));
                         }
                         $_pages[$title] = $temp->evaluate();
                         // FUDGEFUDGE
                     }
                 }
             }
             $url = new ocp_tempcode();
             if ($_pages != array()) {
                 $keys = array_keys($_pages);
                 $first = $_pages[$keys[0]];
                 ksort($_pages);
                 $_pages = array($keys[0] => $first) + $_pages;
             }
             $temp = do_template('BLOCK_MAIN_SITEMAP_NEST', array('_GUID' => '38abb0a0e5bec968b28b4791320dd0dc', 'URL' => $url, 'NAME' => $zone_title, 'CHILDREN' => $_pages));
             $_zones[] = $temp->evaluate();
             // FUDGEFUDGE
         }
     }
     // To avoid running out of memory
     $out = do_template('BLOCK_MAIN_SITEMAP', array('_GUID' => 'd0807b30925e47d10cdb2c36231436ab', 'CHILDREN' => $_zones));
     $e = $out->evaluate();
     $explode = explode('__keep__', $e);
     // the URLs are build without keep and the templates tack it on the end
     if (strpos($e, '__keep__') !== false) {
         $out = new ocp_tempcode();
         foreach ($explode as $i => $bit) {
             if ($i != 0) {
                 $out->attach(symbol_tempcode('KEEP', NULL, array(ENTITY_ESCAPED)));
             }
             if ($GLOBALS['XSS_DETECT']) {
                 ocp_mark_as_escaped($bit);
             }
             $out->attach($bit);
         }
     }
     $e = $out->evaluate();
     if (strpos($e, '__keep1__') !== false) {
         $explode = explode('__keep1__', $e);
         $out = new ocp_tempcode();
         foreach ($explode as $i => $bit) {
             if ($i != 0) {
                 $out->attach(symbol_tempcode('KEEP', array('1'), array(ENTITY_ESCAPED)));
             }
             if ($GLOBALS['XSS_DETECT']) {
                 ocp_mark_as_escaped($bit);
             }
             $out->attach($bit);
         }
     }
     return $out;
 }
Beispiel #29
0
/**
 * Convert a language string into another language string.
 *
 * @param  mixed			The string to convert
 * @param  LONG_TEXT		The language to convert to
 * @return LONG_TEXT		The converted string
 */
function google_translate($str_in, $lang)
{
    $tempcode = is_object($str_in);
    $GLOBALS['NO_QUERY_LIMIT'] = true;
    if (get_option('enable_google_translate', true) !== '1') {
        return $str_in;
    }
    if ($tempcode) {
        $str_in = $str_in->evaluate();
    }
    global $DOING_TRANSLATE;
    if (!isset($DOING_TRANSLATE)) {
        $DOING_TRANSLATE = false;
    }
    if ($DOING_TRANSLATE) {
        return $tempcode ? protect_from_escaping($str_in) : $str_in;
    }
    // Don't want loops
    if ($str_in == '') {
        return $tempcode ? protect_from_escaping(escape_html('')) : escape_html('');
    }
    if (strpos($str_in, 'gtranslate_cache') !== false) {
        return $tempcode ? protect_from_escaping($str_in) : $str_in;
    }
    // Stop loops about corrupt/missing database tables
    $language_list = array('ar' => 'Arabic', 'bg' => 'Bulgarian', 'zh-cn' => 'Simplified Chinese', 'zh-tw' => 'Traditional Chinese', 'hr' => 'Croatian', 'cs' => 'Czech', 'da' => 'Danish', 'nl' => 'Dutch', 'en' => 'English', 'fi' => 'Finnish', 'fr' => 'French', 'de' => 'German', 'el' => 'Greek', 'hi' => 'Hindi', 'it' => 'Italian', 'ja' => 'Japanese', 'ko' => 'Korean', 'pl' => 'Polish', 'pt' => 'Portuguese', 'ro' => 'Romanian', 'ru' => 'Russian', 'es' => 'Spanish', 'sv' => 'Swedish');
    $lang = strtolower($lang);
    if (!array_key_exists($lang, $language_list)) {
        return $tempcode ? protect_from_escaping($str_in) : $str_in;
    }
    $DOING_TRANSLATE = true;
    require_lang('lang');
    $chache = check_google_cache($str_in, $lang);
    if (count($chache) == 0) {
        require_code('GTranslate');
        $translate = new GTranslate();
        $num_matches = array();
        $matches = array();
        $rep = array();
        $prepped = $str_in;
        $j = 0;
        foreach (array(array('[', ']'), array('{', '}')) as $symbol) {
            $_matches = array();
            $_num_matches = preg_match_all('#[' . preg_quote($symbol[0]) . '][^' . preg_quote($symbol[0]) . preg_quote($symbol[1]) . ']*[' . preg_quote($symbol[1]) . ']#', $str_in, $_matches);
            $matches[$symbol[0]] = $_matches;
            $num_matches[$symbol[0]] = $_num_matches;
            for ($i = 0; $i < $_num_matches; $i++) {
                $from = $_matches[0][$i];
                $to = '<span class="notranslate">' . strval($j) . '</span>';
                $rep['!' . strval($j)] = $from;
                // The '!' bit is because we can't trust indexing in PHP arrays if it is numeric
                $pos = 0;
                do {
                    $pos = strpos($prepped, $from, $pos);
                    if ($pos !== false) {
                        $pos_open = strrpos(substr($prepped, 0, $pos), '<');
                        $pos_close = strrpos(substr($prepped, 0, $pos), '>');
                        if ($pos_open === false || $pos_close !== false && $pos_close > $pos_open) {
                            $prepped = substr($prepped, 0, $pos) . $to . substr($prepped, $pos + strlen($from));
                            $pos += strlen($to);
                        } else {
                            $pos_title = strrpos(substr($prepped, 0, $pos), 'title="');
                            $pos_alt = strrpos(substr($prepped, 0, $pos), 'alt="');
                            $pos_quote = strrpos(substr($prepped, 0, $pos), '"');
                            if ($pos_alt !== false && $pos_alt > $pos_open && $pos_quote == $pos_alt + 4 || $pos_title !== false && $pos_title > $pos_open && $pos_quote == $pos_title + 6) {
                                $to2 = ' conv' . strval($j) . ' ';
                                $prepped = substr($prepped, 0, $pos) . $to2 . substr($prepped, $pos + strlen($from));
                                $pos += strlen($to2);
                            } else {
                                $pos += strlen($from);
                            }
                        }
                    }
                } while ($pos !== false);
                $j++;
            }
        }
        if (strpos(preg_replace('#<[^>]*>#', '', $prepped), '{') !== false) {
            $DOING_TRANSLATE = false;
            return $tempcode ? protect_from_escaping($str_in) : $str_in;
            // Cannot translate as it has very complex Tempcode in it
        }
        $to = $language_list[$lang];
        $from_lang = strtolower(get_site_default_lang());
        try {
            $convertedstring = $translate->Text($prepped)->From(array_key_exists($from_lang, $language_list) ? $language_list[$from_lang] : 'English')->To($to);
        } catch (Exception $e) {
        }
        if ($convertedstring === NULL) {
            $convertedstring = $str_in;
        }
        do {
            $before = $convertedstring;
            $convertedstring = preg_replace('#(<span class="notranslate">\\d+) (.*</span>)#', '${1}</span> <span class="notranslate">${2}', $convertedstring);
        } while ($before != $convertedstring);
        foreach (array_reverse($rep) as $_j => $from) {
            $j = intval(substr($_j, 1));
            $convertedstring = preg_replace('#\\s*<span class="notranslate">\\s*' . preg_quote(strval($j)) . '\\s*</span>\\s*#', $from, $convertedstring);
            $convertedstring = preg_replace('# conv' . preg_quote(strval($j)) . '\\s*#', $from, $convertedstring);
        }
        $convertedstring = str_replace('<html> ', '', $convertedstring);
        $convertedstring = str_replace('&#39;', '', $convertedstring);
        save_google_cache($str_in, $lang, $convertedstring);
        $str = $convertedstring;
    } else {
        $str = $chache['t_result'];
    }
    $DOING_TRANSLATE = false;
    if (function_exists('ocp_mark_as_escaped') && ocp_is_escaped($str_in)) {
        ocp_mark_as_escaped($str);
    }
    return $tempcode ? protect_from_escaping($str) : $str;
}
Beispiel #30
0
 /**
  * This function is a very basic query executor. It shouldn't usually be used by you, as there are abstracted versions available.
  *
  * @param  string			The complete SQL query
  * @param  array			A DB connection
  * @param  ?integer		The maximum number of rows to affect (NULL: no limit)
  * @param  ?integer		The start row to affect (NULL: no specification)
  * @param  boolean		Whether to output an error on failure
  * @param  boolean		Whether to get the autoincrement ID created for an insert query
  * @return ?mixed			The results (NULL: no results), or the insert ID
  */
 function db_query($query, $db_parts, $max = NULL, $start = NULL, $fail_ok = false, $get_insert_id = false)
 {
     list($db, $db_name) = $db_parts;
     if (isset($query[500000])) {
         $test_result = $this->db_query('SHOW VARIABLES LIKE \'max_allowed_packet\'', $db_parts, NULL, NULL, true);
         if (!is_array($test_result)) {
             return NULL;
         }
         if (intval($test_result[0]['Value']) < intval(strlen($query) * 1.2)) {
             /*@mysql_query('SET session max_allowed_packet='.strval(intval(strlen($query)*1.3)),$db); Does not work well, as MySQL server has gone away error will likely just happen instead */
             if ($get_insert_id) {
                 fatal_exit(do_lang_tempcode('QUERY_FAILED_TOO_BIG', escape_html($query)));
             }
             return NULL;
         }
     }
     global $LAST_SELECT_DB;
     if ($LAST_SELECT_DB[1] != $db_name) {
         mysqli_select_db($db, $db_name);
         $LAST_SELECT_DB = array($db, $db_name);
     }
     if ($max !== NULL && $start !== NULL) {
         $query .= ' LIMIT ' . strval($start) . ',' . strval($max);
     } elseif ($max !== NULL) {
         $query .= ' LIMIT ' . strval($max);
     } elseif ($start !== NULL) {
         $query .= ' LIMIT ' . strval($start) . ',30000000';
     }
     $results = @mysqli_query($db, $query);
     if ($results === false && (!$fail_ok || strpos(mysqli_error($db), 'is marked as crashed and should be repaired') !== false)) {
         $err = mysqli_error($db);
         if (function_exists('mysqli_ping') && $err == 'MySQL server has gone away' && !isset($GLOBALS['REDONE_ONCE'])) {
             $GLOBALS['REDONE_ONCE'] = true;
             mysqli_ping($db);
             $ret = $this->db_query($query, $db_parts, $max, $start, $fail_ok, $get_insert_id);
             unset($GLOBALS['REDONE_ONCE']);
             return $ret;
         }
         if (function_exists('ocp_mark_as_escaped')) {
             ocp_mark_as_escaped($err);
         }
         if (!running_script('upgrader') && get_page_name() != 'admin_import') {
             if (!function_exists('do_lang') || is_null(do_lang('QUERY_FAILED', NULL, NULL, NULL, NULL, false))) {
                 fatal_exit(htmlentities('Query failed: ' . $query . ' : ' . $err));
             }
             fatal_exit(do_lang_tempcode('QUERY_FAILED', escape_html($query), $err));
         } else {
             echo htmlentities('Database query failed: ' . $query . ' [') . $err . htmlentities(']' . '<br />' . chr(10));
             return NULL;
         }
     }
     if ($results !== true && (strtoupper(substr($query, 0, 7)) == 'SELECT ' || strtoupper(substr($query, 0, 8)) == '(SELECT ' || strtoupper(substr($query, 0, 8)) == 'EXPLAIN ' || strtoupper(substr($query, 0, 9)) == 'DESCRIBE ' || strtoupper(substr($query, 0, 5)) == 'SHOW ') && $results !== false) {
         return $this->db_get_query_rows($results);
     }
     if ($get_insert_id) {
         if (strtoupper(substr($query, 0, 7)) == 'UPDATE ') {
             return mysqli_affected_rows($db);
         }
         $ins = mysqli_insert_id($db);
         if ($ins === 0) {
             $table = substr($query, 12, strpos($query, ' ', 12) - 12);
             $rows = $this->db_query('SELECT MAX(id) AS x FROM ' . $table, $db_parts, 1, 0, false, false);
             return $rows[0]['x'];
         }
         return $ins;
     }
     return NULL;
 }