Пример #1
0
 /**
  * Forum_Controller constructor
  * @param string template	The base template to use for
  *							the specific page.
  */
 function Forum_Controller($template)
 {
     /* Globalize the settings and config arrays */
     global $_SETTINGS, $_USERGROUPS, $_ALLFORUMS;
     /* Make sure the default event class exists */
     if (!class_exists('DefaultEvent')) {
         exit('Yahtzee!');
     }
     /* Call the Controller Constructor */
     parent::Controller(new DefaultEvent());
     /* Create a new instance of Template */
     error::reset();
     $this->template =& new Template($template);
     if (error::grab()) {
         critical_error();
     }
     /* Set all of the setting values to the template */
     $this->template->setVarArray($_SETTINGS);
     /* Set the Jump To Box */
     $jump_to =& new AllForumsIterator($_ALLFORUMS);
     $this->template->setList('all_forums', $jump_to);
     /* Add the usergroups to the template */
     $usergroups =& new FAArrayIterator($_USERGROUPS);
     $this->template->setList('usergroups', $usergroups);
 }
Пример #2
0
 function operation($x18 = true)
 {
     if ($this->sql === null) {
         return;
     }
     $this->sql = (string) @trim($this->sql);
     $this->time_query = $this->_mctime();
     switch ($this->type) {
         case 'mysql':
             $x19 = $this->MySql($x18);
             break;
         default:
             $x19 = false;
             break;
     }
     if ($x19 !== false) {
         $this->time_query = round($this->_mctime() - $this->time_query, 4);
         $this->AllTimeQueries += $this->time_query;
         $x1a =& $this->sqls[];
         $x1a['operation'] = $this->oprt;
         $x1a['file'] = $this->file;
         $x1a['line'] = $this->line;
         $x1a['query'] = $this->sql;
         $x1a['time'] = $this->time_query;
         $x1a['result'] = sizeof($x19);
         $this->id = mysql_insert_id();
         unset($x1a);
         $this->_clear();
         return $x19;
     }
     if ($this->showerr and $this->show_err) {
         if (preg_match('#^[^\']*? \'(.*?)\' in#', mysql_error(), $x1b = null)) {
             $this->sql = str_replace($x1b[1], '<b>' . $x1b[1] . '</b>', $this->sql);
         }
         $x1c = '<B>&#1054;&#1096;&#1080;&#1073;&#1082;&#1072; DB:</B> <BR><BR>' . mysql_error() . ' <BR><BR> ' . $this->sql . '';
         if (function_exists('critical_error')) {
             critical_error($x1c, $this->file, $this->line);
         }
         elsedie($x1c);
     }
     return false;
 }
Пример #3
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (note for mySQL, it's actually a pair, containing the database name too: because we need to select the name before each query on the connection) (NULL: error)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     if (!function_exists('dbx_connect')) {
         $error = 'dbx not on server (anymore?). Try using the \'mysql\' database driver. To use it, edit the info.php config file.';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     // Potential cacheing
     global $CACHE_DB;
     $x = serialize(array($db_name, $db_host));
     if (array_key_exists($x, $CACHE_DB)) {
         return array($x, $db_name);
     }
     $db = @dbx_connect('mysql', $db_host, $db_name, $db_user, $db_password, $persistent ? 1 : 0);
     if ($db === false || is_null($db)) {
         $error = 'Could not connect to database/database-server';
         if ($fail_ok) {
             echo $error . chr(10);
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR')); // purposely not ===false
     }
     global $LAST_SELECT_DB;
     $LAST_SELECT_DB = $db;
     global $SITE_INFO;
     if (!array_key_exists('database_charset', $SITE_INFO)) {
         $SITE_INFO['database_charset'] = strtolower(get_charset()) == 'utf-8' ? 'utf8' : 'latin1';
     }
     @dbx_query($db, 'SET NAMES "' . addslashes($SITE_INFO['database_charset']) . '"');
     @dbx_query($db, 'SET SQL_BIG_SELECTS=1');
     if (get_forum_type() == 'ocf') {
         @dbx_query($db, 'SET sql_mode=STRICT_ALL_TABLES');
     }
     return array($db, $db_name);
 }
//    ""
//   . js_global_variables()
//   . js_xml_http_request_client()
//   . js_request_close_panel()
//   . $js_stack
//
//   . get_tabmenu($s_page)
//    ;
// display the panels on the active page
foreach ($panels as $nr => $panel) {
    // take respect for the $HIDE_PANELS configuration
    if (in_array($panel[0], $HIDE_PANELS) && ($s_login['user'] != 'SYSDBA' || SYSDBA_GET_ALL == FALSE || $s_connected == FALSE)) {
        continue;
    }
    echo '<div id="p' . $nr . "\">\n" . '<a name="' . $panel[0] . '"></a>' . "\n";
    if ($panel[2] == 'open' || $panel[0] == 'info' && critical_error()) {
        echo get_open_panel_start($panel[1], $nr);
        // there may be different instances of the data edit/delete panel,
        // which carrying the instance nr in the panel name
        if (preg_match('/dt_(edit|delete)([0-9]+)/', $panel[0], $matches)) {
            $instance = $matches[2];
            if ($matches[1] == 'edit') {
                include './panels/dt_edit.php';
            } else {
                $subject = 'row';
                include './panels/confirm.php';
            }
        } else {
            include './panels/' . $panel[0] . '.php';
        }
        echo get_open_panel_end();
Пример #5
0
    if ($errorno != 2048 && $errorno != 8) {
        //  E_STRICT & E_NOTICE  && $errorno != 8
        return compile_error($string, $file, $line);
    }
}
set_error_handler("error_handler");
/**
 * Get all of the settings into one big array
 */
/* Get the configuration options */
global $_CONFIG;
/* Get the database Object and set it to a global */
error::reset();
$_DBA =& Database::open($_CONFIG['dba']);
if (error::grab()) {
    return critical_error();
}
$GLOBALS['_DBA'] =& $_DBA;
/*
$query = "";

foreach(explode("\r\n", $query) as $q)
	if($q != '')
		$_DBA->executeUpdate($q);
exit;
*/
/**
 * Create some cache files to reduce queries, but only if it needs to be re/created
 */
$cache = array();
/**
Пример #6
0
/**
 * Load up a language file, compiling it (it's not cached yet).
 *
 * @param  ID_TEXT			The language file name
 * @param  ?LANGUAGE_NAME	The language (NULL: uses the current language)
 * @param  ?string			The language type (lang_custom, or custom) (NULL: normal priorities are used)
 * @set    lang_custom custom
 * @param  PATH				Where we are cacheing too
 * @param  boolean			Whether to just return if there was a loading error
 * @return boolean			Whether we FAILED to load
 */
function require_lang_compile($codename, $lang, $type, $cache_path, $ignore_errors = false)
{
    global $LANGUAGE, $REQUIRE_LANG_LOOP, $LANG_LOADED_LANG;
    $desire_cache = function_exists('get_option') && (get_option('is_on_lang_cache', true) == '1' || get_param_integer('keep_cache', 0) == 1 || get_param_integer('cache', 0) == 1) && get_param_integer('keep_cache', NULL) !== 0 && get_param_integer('cache', NULL) !== 0;
    if ($desire_cache) {
        if ($GLOBALS['IN_MINIKERNEL_VERSION'] == 0) {
            global $DECACHED_COMCODE_LANG_STRINGS;
            // Cleanup language strings
            if (!$DECACHED_COMCODE_LANG_STRINGS) {
                $DECACHED_COMCODE_LANG_STRINGS = true;
                $comcode_lang_strings = $GLOBALS['SITE_DB']->query_select('cached_comcode_pages', array('string_index'), array('the_zone' => '!'), '', NULL, NULL, true);
                if (!is_null($comcode_lang_strings)) {
                    $GLOBALS['SITE_DB']->query_delete('cached_comcode_pages', array('the_zone' => '!'));
                    foreach ($comcode_lang_strings as $comcode_lang_string) {
                        delete_lang($comcode_lang_string['string_index']);
                    }
                }
            }
        }
        $load_target = array();
    } else {
        $load_target =& $LANGUAGE[$lang];
    }
    global $FILE_ARRAY;
    if (@is_array($FILE_ARRAY) && file_array_exists('lang/' . $lang . '/' . $codename . '.ini')) {
        $lang_file = 'lang/' . $lang . '/' . $codename . '.ini';
        $file = file_array_get($lang_file);
        _get_lang_file_map($file, $load_target, NULL, true);
        $bad = true;
    } else {
        $bad = true;
        $dirty = false;
        // Load originals
        $lang_file = get_file_base() . '/lang/' . $lang . '/' . filter_naughty($codename) . '.ini';
        if (file_exists($lang_file)) {
            _get_lang_file_map($lang_file, $load_target, NULL, false);
            $bad = false;
        }
        // Load overrides now if they are there
        if ($type != 'lang') {
            $lang_file = get_custom_file_base() . '/lang_custom/' . $lang . '/' . $codename . '.ini';
            if (!file_exists($lang_file) && get_file_base() != get_custom_file_base()) {
                $lang_file = get_file_base() . '/lang_custom/' . $lang . '/' . $codename . '.ini';
            }
            if (!file_exists($lang_file)) {
                $lang_file = get_custom_file_base() . '/lang_custom/' . $lang . '/' . $codename . '.po';
                if (!file_exists($lang_file)) {
                    $lang_file = get_file_base() . '/lang_custom/' . $lang . '/' . $codename . '-' . strtolower($lang) . '.po';
                }
            }
        }
        if ($type != 'lang' && file_exists($lang_file)) {
            _get_lang_file_map($lang_file, $load_target, NULL, false);
            $bad = false;
            $dirty = true;
            // Tainted from the official pack, so can't store server wide
        }
        // NB: Merge op doesn't happen in require_lang. It happens when do_lang fails and then decides it has to force a recursion to do_lang(xx,fallback_lang()) which triggers require_lang(xx,fallback_lang()) when it sees it's not loaded
        if ($bad && $lang != fallback_lang()) {
            require_lang($codename, fallback_lang(), $type, $ignore_errors);
            $REQUIRE_LANG_LOOP--;
            $fallback_cache_path = get_custom_file_base() . '/lang_cached/' . fallback_lang() . '/' . $codename . '.lcd';
            if (file_exists($fallback_cache_path)) {
                require_code('files');
                @copy($fallback_cache_path, $cache_path);
                fix_permissions($cache_path);
            }
            if (!array_key_exists($lang, $LANG_LOADED_LANG)) {
                $LANG_LOADED_LANG[$lang] = array();
            }
            $LANG_LOADED_LANG[$lang][$codename] = 1;
            return $bad;
        }
        if ($bad) {
            if ($ignore_errors) {
                return true;
            }
            if ($codename != 'critical_error' || $lang != get_site_default_lang()) {
                fatal_exit(do_lang_tempcode('MISSING_LANG_FILE', escape_html($codename), escape_html($lang)));
            } else {
                critical_error('CRIT_LANG');
            }
        }
    }
    if (is_null($GLOBALS['MEM_CACHE'])) {
        // Cache
        if ($desire_cache) {
            $file = @fopen($cache_path, 'wt');
            // Will fail if cache dir missing .. e.g. in quick installer
            if ($file) {
                if (fwrite($file, serialize($load_target)) > 0) {
                    // Success
                    fclose($file);
                    require_code('files');
                    fix_permissions($cache_path);
                } else {
                    // Failure
                    fclose($file);
                    @unlink($cache_path);
                }
            }
        }
    } else {
        persistant_cache_set(array('LANG', $lang, $codename), $load_target, !$dirty);
    }
    if ($desire_cache) {
        $LANGUAGE[$lang] += $load_target;
    }
    return $bad;
}
Пример #7
0
/**
 * Check to see if an IP address is banned.
 *
 * @param  string			The IP address to check for banning (potentially encoded with *'s)
 * @return boolean		Whether the IP address is banned
 */
function ip_banned($ip)
{
    if (!addon_installed('securitylogging')) {
        return false;
    }
    $ip4 = strpos($ip, '.') !== false;
    if ($ip4) {
        $ip_parts = explode('.', $ip);
    } else {
        $ip_parts = explode(':', $ip);
    }
    global $SITE_INFO;
    if (isset($SITE_INFO['known_suexec']) && $SITE_INFO['known_suexec'] == '1' || is_writable_wrap(get_file_base() . '/.htaccess')) {
        $bans = array();
        $ban_count = preg_match_all('#\\ndeny from (.*)#', file_get_contents(get_file_base() . '/.htaccess'), $bans);
        $ip_bans = array();
        for ($i = 0; $i < $ban_count; $i++) {
            $ip_bans[] = array('ip' => $bans[1][$i]);
        }
    } else {
        $ip_bans = persistant_cache_get('IP_BANS');
        if (!is_array($ip_bans)) {
            $ip_bans = $GLOBALS['SITE_DB']->query('SELECT ip FROM ' . get_table_prefix() . 'usersubmitban_ip', NULL, NULL, true);
            if (!is_null($ip_bans)) {
                persistant_cache_set('IP_BANS', $ip_bans);
            }
        }
        if (is_null($ip_bans)) {
            critical_error('DATABASE_FAIL');
        }
    }
    $self_ip = NULL;
    foreach ($ip_bans as $ban) {
        if ($ip4 && compare_ip_address_ip4($ban['ip'], $ip_parts) || !$ip4 && compare_ip_address_ip6($ban['ip'], $ip_parts)) {
            if (is_null($self_ip)) {
                $self_host = ocp_srv('HTTP_HOST');
                if ($self_host == '' || preg_match('#^localhost[\\.\\:$]#', $self_host) != 0) {
                    $self_ip = '';
                } else {
                    if (preg_match('#(\\s|,|^)gethostbyname(\\s|$|,)#i', @ini_get('disable_functions')) == 0) {
                        $self_ip = gethostbyname($self_host);
                    } else {
                        $self_ip = '';
                    }
                    if ($self_ip == '') {
                        $self_ip = ocp_srv('SERVER_ADDR');
                    }
                }
            }
            if ($self_ip != '' && compare_ip_address($ban['ip'], $self_ip)) {
                continue;
            }
            if (compare_ip_address($ban['ip'], '127.0.0.1')) {
                continue;
            }
            if (compare_ip_address($ban['ip'], 'fe00:0000:0000:0000:0000:0000:0000:0000')) {
                continue;
            }
            return true;
        }
    }
    return false;
}
Пример #8
0
/**
 * Attach a message to the page output.
 *
 * @param  mixed			The type of special message
 * @param  ID_TEXT		The template to use
 * @set    inform notice warn
 * @return string			Blank string so it can be chained in the Tempcode compiler. You will rarely want to use this return value. It's kind of a failsafe.
 */
function attach_message($message, $type = 'inform')
{
    if (error_reporting() == 0 && $type == 'warn') {
        return '';
    }
    // Suppressing errors
    static $am_looping = false;
    if ($am_looping) {
        return '';
    }
    // Was a lang lookup error and got in an infinite loop of attaching errors about missing lang errors (because each iteration causes a reevaluation of past messages)
    $am_looping = true;
    global $DONE_HEADER, $ATTACH_MESSAGE_CALLED, $ATTACHED_MESSAGES, $ATTACHED_MESSAGES_RAW;
    foreach ($ATTACHED_MESSAGES_RAW as $last) {
        if (array(is_object($last[0]) ? $last[0]->evaluate() : $last[0], $last[1]) == array(is_object($message) ? $message->evaluate() : $message, $type)) {
            $am_looping = false;
            return '';
            // Already shown
        }
    }
    $ATTACH_MESSAGE_CALLED++;
    if ($ATTACH_MESSAGE_CALLED > 5) {
        critical_error('EMERGENCY', is_object($message) ? $message->evaluate() : escape_html($message));
    }
    if ($DONE_HEADER) {
        // Drastic measures
        global $FAILED_TO_ATTACH_ALL_ERRORS;
        if (!$FAILED_TO_ATTACH_ALL_ERRORS) {
            // Okay, start recording what will be shown on the bottom from this point
            $ATTACHED_MESSAGES = new ocp_tempcode();
            $ATTACHED_MESSAGES_RAW = array();
            $FAILED_TO_ATTACH_ALL_ERRORS = true;
        }
    }
    if ($type == 'warn' && strlen(is_object($message) ? $message->evaluate() : $message) < 130) {
        require_code('failure');
        $webservice_result = get_webservice_result($message);
        if ($webservice_result !== NULL) {
            if (is_object($message) && $message->pure_lang) {
                $message = $message->evaluate();
            } elseif (is_object($message)) {
                $message = escape_html($message->evaluate());
            } else {
                $message = escape_html($message);
            }
            $message = do_template('CROP_TEXT_MOUSE_OVER', array('TEXT_LARGE' => $webservice_result, 'TEXT_SMALL' => protect_from_escaping($message)));
            $message = protect_from_escaping($message);
        }
    }
    if (get_param_integer('keep_fatalistic', 0) == 1 && $type == 'warn') {
        fatal_exit($message);
    }
    $ATTACHED_MESSAGES_RAW[] = array($message, $type);
    $message = do_template('ADDITIONAL', array('_GUID' => 'ec843c8619d21fbeeb512686ea300a17', 'TYPE' => $type, 'MESSAGE' => is_string($message) ? escape_html($message) : $message));
    $ATTACHED_MESSAGES->attach($message);
    $ATTACH_MESSAGE_CALLED--;
    $am_looping = false;
    return '';
}
Пример #9
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (NULL: failed)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     // Potential cacheing
     global $CACHE_DB;
     if (isset($CACHE_DB[$db_name][$db_host])) {
         return $CACHE_DB[$db_name][$db_host];
     }
     if (!function_exists('pg_pconnect')) {
         $error = 'The postgreSQL PHP extension not installed (anymore?). You need to contact the system administrator of this server.';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     $db = $persistent ? @pg_pconnect('host=' . $db_host . ' dbname=' . $db_name . ' user='******' password='******'host=' . $db_host . ' dbname=' . $db_name . ' user='******' password='******'Could not connect to database-server (' . @pg_last_error() . ')';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
     }
     if (!$db) {
         fatal_exit(do_lang('CONNECT_DB_ERROR'));
     }
     $CACHE_DB[$db_name][$db_host] = $db;
     return $db;
 }
Пример #10
0
/**
 * Get the human-readable form of a language id, or a language entry from a language INI file.
 *
 * @param  ID_TEXT		The language id
 * @param  ?mixed			The first token [string or tempcode] (replaces {1}) (NULL: none)
 * @param  ?mixed			The second token [string or tempcode] (replaces {2}) (NULL: none)
 * @param  ?mixed			The third token (replaces {3}). May be an array of [of string], to allow any number of additional args (NULL: none)
 * @param  ?LANGUAGE_NAME The language to use (NULL: users language)
 * @param  boolean		Whether to cause ocPortal to exit if the lookup does not succeed
 * @return ?mixed			The human-readable content (NULL: not found). String normally. Tempcode if tempcode parameters.
 */
function _do_lang($codename, $token1 = NULL, $token2 = NULL, $token3 = NULL, $lang = NULL, $require_result = true)
{
    global $LANGUAGE, $USER_LANG_CACHED, $RECORD_LANG_STRINGS, $XSS_DETECT, $PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED;
    if ($lang === NULL) {
        $lang = $USER_LANG_CACHED === NULL ? user_lang() : $USER_LANG_CACHED;
    }
    if ($GLOBALS['SEMI_DEBUG_MODE']) {
        $pos = strpos($codename, '=');
        if ($pos !== false) {
            // Find loaded file with smallest levenstein distance to current page
            $best = mixed();
            $best_for = NULL;
            global $LANGS_REQUESTED;
            foreach (array_keys($LANGS_REQUESTED) as $possible) {
                $dist = levenshtein(get_page_name(), $possible);
                if (is_null($best) || $best > $dist) {
                    $best = $dist;
                    $best_for = $possible;
                }
            }
            $save_path = get_file_base() . '/lang/' . fallback_lang() . '/' . $best_for . '.ini';
            if (!is_file($save_path)) {
                $save_path = get_file_base() . '/lang_custom/' . fallback_lang() . '/' . $best_for . '.ini';
            }
            // Tack language strings onto this file
            list($codename, $value) = explode('=', $codename, 2);
            $myfile = fopen($save_path, 'at');
            fwrite($myfile, "\n" . $codename . '=' . $value);
            fclose($myfile);
            // Fake-load the string
            $LANGUAGE[$lang][$codename] = $value;
            // Go through all required files, doing a string replace if needed
            $included_files = get_included_files();
            foreach ($included_files as $inc) {
                $orig_contents = file_get_contents($inc);
                $contents = str_replace("'" . $codename . '=' . $value . "'", "'" . $codename . "'", $orig_contents);
                if ($orig_contents != $contents) {
                    $myfile = fopen($inc, 'wt');
                    fwrite($myfile, $contents);
                    fclose($myfile);
                }
            }
        }
    }
    $there = isset($LANGUAGE[$lang][$codename]);
    if (!$there) {
        $pos = strpos($codename, ':');
        if ($pos !== false) {
            require_lang(substr($codename, 0, $pos), NULL, NULL, !$require_result);
            $codename = substr($codename, $pos + 1);
        }
        $there = isset($LANGUAGE[$lang][$codename]);
    }
    if ($RECORD_LANG_STRINGS) {
        global $RECORDED_LANG_STRINGS;
        $RECORDED_LANG_STRINGS[$codename] = 1;
    }
    if (!$there && (!isset($LANGUAGE[$lang]) || !array_key_exists($codename, $LANGUAGE[$lang]))) {
        global $PAGE_CACHE_LAZY_LOAD, $PAGE_CACHE_LANGS_REQUESTED, $LANG_REQUESTED_LANG;
        if ($PAGE_CACHE_LAZY_LOAD) {
            $PAGE_CACHE_LAZY_LOAD = false;
            // We can't be lazy any more, but we will keep growing our pool so hopefully CAN be lazy the next time
            foreach ($PAGE_CACHE_LANGS_REQUESTED as $request) {
                list($that_codename, $that_lang) = $request;
                unset($LANG_REQUESTED_LANG[$that_lang][$that_codename]);
                require_lang($that_codename, $that_lang, NULL, true);
            }
            $ret = _do_lang($codename, $token1, $token2, $token3, $lang, $require_result);
            if ($ret === NULL) {
                $PAGE_CACHE_LANG_LOADED[$lang][$codename] = NULL;
                if ($GLOBALS['MEM_CACHE'] !== NULL) {
                    persistant_cache_set($PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED);
                } else {
                    open_page_cache_file();
                    @rewind($PAGE_CACHE_FILE);
                    @flock($PAGE_CACHE_FILE, LOCK_EX);
                    @ftruncate($PAGE_CACHE_FILE, 0);
                    @fwrite($PAGE_CACHE_FILE, serialize($PAGE_CACHE_LANG_LOADED));
                    @flock($PAGE_CACHE_FILE, LOCK_UN);
                }
            }
            return $ret;
        }
        require_all_open_lang_files($lang);
    }
    if ($lang == 'xxx') {
        return 'xxx';
    }
    // Helpful for testing language compliancy. We don't expect to see non x's if we're running this language
    if (!isset($LANGUAGE[$lang][$codename]) && ($require_result || !isset($LANGUAGE[$lang]) || !array_key_exists($codename, $LANGUAGE[$lang]))) {
        if ($lang != fallback_lang()) {
            $ret = do_lang($codename, $token1, $token2, $token3, fallback_lang(), $require_result);
            if ($PAGE_CACHE_FILE !== NULL) {
                if (!isset($PAGE_CACHE_LANG_LOADED[$lang][$codename]) && isset($PAGE_CACHE_LANG_LOADED[fallback_lang()][$codename])) {
                    $PAGE_CACHE_LANG_LOADED[$lang][$codename] = $PAGE_CACHE_LANG_LOADED[fallback_lang()][$codename];
                    // Will have been cached into fallback_lang() from the nested do_lang call, we need to copy it into our cache bucket for this language
                    if ($GLOBALS['MEM_CACHE'] !== NULL) {
                        persistant_cache_set($PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED);
                    } else {
                        open_page_cache_file();
                        @rewind($PAGE_CACHE_FILE);
                        @flock($PAGE_CACHE_FILE, LOCK_EX);
                        @ftruncate($PAGE_CACHE_FILE, 0);
                        @fwrite($PAGE_CACHE_FILE, serialize($PAGE_CACHE_LANG_LOADED));
                        @flock($PAGE_CACHE_FILE, LOCK_UN);
                    }
                }
            }
            return $ret;
        } else {
            if ($require_result) {
                global $USER_LANG_LOOP, $REQUIRE_LANG_LOOP;
                //print_r(debug_backtrace());
                if ($USER_LANG_LOOP == 1) {
                    critical_error('RELAY', 'Missing language code: ' . escape_html($codename) . '. This language code is required to produce error messages, and thus a critical error was prompted by the non-ability to show less-critical error messages. It is likely the source language files (lang/' . fallback_lang() . '/*.ini) for ocPortal on this website have been corrupted.');
                }
                if ($REQUIRE_LANG_LOOP >= 2) {
                    return '';
                }
                // Probably failing to load global.ini, so just output with some text missing
                require_code('view_modes');
                erase_cached_language();
                require_code('site');
                attach_message(do_lang_tempcode('MISSING_LANG_ENTRY', escape_html($codename)), 'warn');
                return '';
            } else {
                return NULL;
            }
        }
    }
    if ($PAGE_CACHE_FILE !== NULL) {
        if (!isset($PAGE_CACHE_LANG_LOADED[$lang][$codename]) && (!isset($PAGE_CACHE_LANG_LOADED[$lang]) || !array_key_exists($codename, $PAGE_CACHE_LANG_LOADED[$lang]))) {
            $PAGE_CACHE_LANG_LOADED[$lang][$codename] = $LANGUAGE[$lang][$codename];
            if ($GLOBALS['MEM_CACHE'] !== NULL) {
                persistant_cache_set($PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED);
            } else {
                open_page_cache_file();
                @rewind($PAGE_CACHE_FILE);
                @flock($PAGE_CACHE_FILE, LOCK_EX);
                @ftruncate($PAGE_CACHE_FILE, 0);
                @fwrite($PAGE_CACHE_FILE, serialize($PAGE_CACHE_LANG_LOADED));
                @flock($PAGE_CACHE_FILE, LOCK_UN);
            }
        }
    }
    // Put in parameters
    static $non_plural_non_vowel = array('1', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', '{');
    $looked_up = $LANGUAGE[$lang][$codename];
    if ($looked_up === NULL) {
        return NULL;
        // Learning cache pool has told us this string definitely does not exist
    }
    $out = str_replace('\\n', "\n", $looked_up);
    $plural_or_vowel_check = strpos($out, '|') !== false;
    if ($XSS_DETECT) {
        ocp_mark_as_escaped($out);
    }
    if ($token1 !== NULL) {
        if (is_object($token1) && $token2 === NULL || $token2 !== NULL && is_object($token2)) {
            $bits = preg_split('#\\{\\d[^\\}]*\\}#', $out, 2, PREG_SPLIT_OFFSET_CAPTURE);
            $ret = new ocp_tempcode();
            foreach ($bits as $bit) {
                if ($XSS_DETECT) {
                    ocp_mark_as_escaped($bit[0]);
                }
                $at = $bit[1];
                if ($at != 0) {
                    if ($out[$at - 2] == '1') {
                        $ret->attach($token1);
                    } elseif ($out[$at - 2] == '2') {
                        $ret->attach($token2);
                    } elseif ($plural_or_vowel_check && substr($out[$at - 2], 0, 2) == '1|') {
                        $exploded = explode('|', $out[$at - 2]);
                        $_token = $token1->evaluate();
                        $_token_denum = str_replace(',', '', $_token);
                        $ret->attach(in_array(is_numeric($_token_denum) ? $_token_denum : ocp_mb_strtolower(ocp_mb_substr($_token, 0, 1)), $non_plural_non_vowel) ? $exploded[1] : $exploded[2]);
                    } elseif ($plural_or_vowel_check && substr($out[$at - 2], 0, 2) == '2|') {
                        $exploded = explode('|', $out[$at - 2]);
                        $_token = $token2->evaluate();
                        $_token_denum = str_replace(',', '', $_token);
                        $ret->attach(in_array(is_numeric($_token_denum) ? $_token_denum : ocp_mb_strtolower(ocp_mb_substr($_token, 0, 1)), $non_plural_non_vowel) ? $exploded[1] : $exploded[2]);
                    }
                }
                $ret->attach($bit[0]);
            }
            return $ret;
        } elseif ($token1 !== NULL) {
            $out = str_replace('{1}', $token1, $out);
            if ($plural_or_vowel_check) {
                $_token_denum = str_replace(',', '', $token1);
                $out = preg_replace('#\\{1\\|(.*)\\|(.*)\\}#U', in_array(is_numeric($_token_denum) ? $_token_denum : ocp_mb_strtolower(ocp_mb_substr($token1, 0, 1)), $non_plural_non_vowel) ? '\\1' : '\\2', $out);
            }
            if ($XSS_DETECT && ocp_is_escaped($token1)) {
                ocp_mark_as_escaped($out);
            }
        }
        if ($token2 !== NULL) {
            if ($XSS_DETECT) {
                $escaped = ocp_is_escaped($out);
            }
            $out = str_replace('{2}', $token2, $out);
            if ($plural_or_vowel_check) {
                $_token_denum = str_replace(',', '', $token1);
                $out = preg_replace('#\\{2\\|(.*)\\|(.*)\\}#U', in_array(is_numeric($_token_denum) ? $_token_denum : ocp_mb_strtolower(ocp_mb_substr($token2, 0, 1)), $non_plural_non_vowel) ? '\\1' : '\\2', $out);
            }
            if ($XSS_DETECT && ocp_is_escaped($token2) && $escaped) {
                ocp_mark_as_escaped($out);
            }
            if ($token3 !== NULL) {
                $i = 3;
                if (!is_array($token3)) {
                    $token3 = array($token3);
                }
                foreach ($token3 as $token) {
                    if ($XSS_DETECT) {
                        $escaped = ocp_is_escaped($out);
                    }
                    $out = str_replace('{' . strval($i) . '}', $token, $out);
                    if ($plural_or_vowel_check) {
                        $_token_denum = str_replace(',', '', $token);
                        $out = preg_replace('#\\{' . strval($i) . '\\|(.*)\\|(.*)\\}#U', in_array(is_numeric($_token_denum) ? $_token_denum : ocp_mb_strtolower(ocp_mb_substr($token, 0, 1)), $non_plural_non_vowel) ? '\\1' : '\\2', $out);
                    }
                    if ($XSS_DETECT && ocp_is_escaped($token) && $escaped) {
                        ocp_mark_as_escaped($out);
                    }
                    $i++;
                }
            }
        }
    }
    return $out;
}
Пример #11
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (note for mySQL, it's actually a pair, containing the database name too: because we need to select the name before each query on the connection) (NULL: failed)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     // Potential cacheing
     global $CACHE_DB, $LAST_SELECT_DB;
     $x = serialize(array($db_name, $db_host));
     if (array_key_exists($x, $CACHE_DB)) {
         if ($LAST_SELECT_DB != $db_name) {
             mysql_select_db($db_name, $x);
             $LAST_SELECT_DB = $db_name;
         }
         return array($x, $db_name);
     }
     if (!function_exists('mysql_connect')) {
         $error = 'The mySQL PHP extension not installed (anymore?). You need to contact the system administrator of this server, or use a different mySQL database driver (drivers can be chosen by editing info.php).';
         if ($fail_ok) {
             echo $error . chr(10);
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     if (defined('HIPHOP_PHP') && $db_host == 'localhost') {
         $db_host = '127.0.0.1';
     }
     $db = $persistent ? @mysql_pconnect($db_host, $db_user, $db_password) : @mysql_connect($db_host, $db_user, $db_password);
     if ($db === false) {
         $error = 'Could not connect to database-server (' . mysql_error() . ', ' . escape_html(@strval($php_errormsg)) . ')';
         if ($fail_ok) {
             echo $error . chr(10);
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
     }
     if (!mysql_select_db($db_name, $db)) {
         if ($db_user == 'root') {
             @mysql_query('CREATE DATABASE IF NOT EXISTS ' . $db_name, $db);
         }
         if (!mysql_select_db($db_name, $db)) {
             $error = 'Could not connect to database (' . mysql_error() . ')';
             if ($fail_ok) {
                 echo $error . chr(10);
                 return NULL;
             }
             critical_error('PASSON', $error);
             //warn_exit(do_lang_tempcode('CONNECT_ERROR'));
         }
     }
     $LAST_SELECT_DB = $db_name;
     global $SITE_INFO;
     if (!array_key_exists('database_charset', $SITE_INFO)) {
         $SITE_INFO['database_charset'] = strtolower(get_charset()) == 'utf-8' ? 'utf8' : 'latin1';
     }
     if (function_exists('mysql_set_charset')) {
         mysql_set_charset($SITE_INFO['database_charset'], $db);
     } else {
         @mysql_query('SET NAMES "' . addslashes($SITE_INFO['database_charset']) . '"', $db);
     }
     @mysql_query('SET WAIT_TIMEOUT=28800', $db);
     @mysql_query('SET SQL_BIG_SELECTS=1', $db);
     if (get_forum_type() == 'ocf' && $GLOBALS['IN_MINIKERNEL_VERSION'] == 0) {
         @mysql_query('SET sql_mode=STRICT_ALL_TABLES', $db);
     } else {
         @mysql_query('SET sql_mode=MYSQL40', $db);
     }
     /*$mysql_version=mysql_get_server_info($db);
     		if (($mysql_version[0]=='3') && (!file_exists(get_file_base().'/old_mysql'))) exit('The mySQL version used is too old (Version '.$mysql_version.' used, whilst at least Version 4.0 is required)');*/
     return array($db, $db_name);
 }
Пример #12
0
 /**
  * The function which calls everything from the controller
  * and render the template(s).
  * @param mixed template	The template variable, holds all current
  *							template information
  * @param mixed session		The session variable, holds all current
  *							session information
  * @return					method template render
  * @see Template
  * @see Session
  */
 function Execute(&$template)
 {
     global $_DBA, $_URL, $_SETTINGS;
     /**
      * General Variable Setting
      */
     /* Start the timer */
     $this->timer =& new Timer();
     /* Merge the post and get arrays */
     $request = array_merge($this->get, $this->post, $this->cookie);
     /* Strip annoying slashes on everything */
     foreach ($request as $key => $val) {
         if (!is_array($val)) {
             $request[$key] = stripslashes($val);
         }
     }
     $result = FALSE;
     /* Get the act var */
     $act_var = get_setting('application', 'action_var') or $act_var = 'act';
     /* get the session and user variables */
     $session =& $_SESSION;
     $user =& $_SESSION['user']->info;
     /**
      * Member/Guest Settings
      */
     /* Figure out which styleset, imageset and templateset to use */
     $styleset = is_a($session['user'], 'Member') && $user['styleset'] != '' || is_a($session['user'], 'Guest') && $user['styleset'] != '' ? $user['styleset'] : $template->getVar('styleset');
     $imageset = is_a($session['user'], 'Member') && $user['imgset'] != '' ? $user['imgset'] : $template->getVar('imageset');
     $templateset = is_a($session['user'], 'Member') && $user['tplset'] != '' ? $user['tplset'] : $template->getVar('templateset');
     /* Set the style, template and image sets */
     $this->template->setVar('css_styles', get_cached_styleset($styleset, $template->getVar('styleset')));
     $template_dir = FORUM_BASE_DIR . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR;
     $imgs_dir = FORUM_BASE_DIR . DIRECTORY_SEPARATOR . 'Images' . DIRECTORY_SEPARATOR;
     /* Should we get the template set that goes with this styleset? */
     $templateset = is_dir($template_dir . $styleset) ? $template_dir . $styleset : $template_dir . $templateset;
     /* Should we get the image set that goes with this styleset? */
     $imageset = is_dir($imgs_dir . $styleset) ? $styleset : $imageset;
     /* Check to see if our templates directory exists */
     if (!is_dir($templateset)) {
         exit('Invalid template set for: ' . $templateset);
     }
     /* Check to see if our images directory exists */
     if (!is_dir($imgs_dir . $imageset)) {
         exit('Invalid image set for: ' . $imageset);
     }
     /* Set the template an image sets */
     $this->template->setDirname($templateset);
     $this->template->setVar('IMG_DIR', $imageset);
     /* Determine which language to get, and then include the appropriate file */
     $language = is_a($session['user'], 'Member') ? strtolower($user['language']) : strtolower(get_setting('application', 'lang'));
     /* Check to see if this is an invalid language file */
     if (!file_exists(FORUM_BASE_DIR . '/includes/lang/' . $language . '/lang.php')) {
         exit('Invalid Language file.');
     }
     /* Require the language file */
     include FORUM_BASE_DIR . '/includes/lang/' . $language . '/lang.php';
     /* Set the language variable to the template */
     $template->setVar('LANG', $language);
     global $lang;
     /* Check if the language function exists */
     if (!isset($lang) || !is_array($lang) || empty($lang)) {
         exit('Invalid Language file.');
     }
     /* Set the locale to which language we are using */
     setlocale(LC_ALL, $lang['locale']);
     /* Set the language array */
     $template->setVarArray($lang);
     /* Memory Saving */
     unset($lang);
     /**
      * Event Execution
      */
     if (get_map($user, 'can_see_board', 'can_view', array()) > $user['perms']) {
         /* This user doesn't have permission to see the bb */
         $template = BreadCrumbs($template, $template->getVar('L_INFORMATION'));
         $template->setInfo('content', $template->getVar('L_YOUNEEDPERMS'));
     } else {
         if (intval($_SETTINGS['bbactive']) == 0 && $user['perms'] < SUPERMOD) {
             /* The board is closed */
             $template = BreadCrumbs($template, $template->getVar('L_INFORMATION'));
             $template->setInfo('content', $_SETTINGS['bbclosedreason']);
         } else {
             /* get the result of our event call */
             if (isset($request[$act_var]) && isset($this->events[$request[$act_var]])) {
                 $result = $this->events[$request[$act_var]]->Execute(&$template, $request, &$_DBA, &$session, &$user);
             }
             /* If the result is false, execute our defaultevent class */
             if ($result == FALSE) {
                 $this->default->Execute(&$template, $request, &$_DBA, &$session, &$user);
             }
         }
     }
     /**
      * User Information
      */
     /* Clear the session and user variables */
     $session =& $_SESSION;
     $user =& $_SESSION['user']->info;
     /**
      * Filters
      */
     /* Apply each Filter to the request */
     for ($i = 0; $i < count($this->filters); $i++) {
         $this->filters[$i]->Execute(&$template, &$session, $this->cookie, $this->post, $this->get);
     }
     /* If the user is logged in, set all of his user info to the template */
     if (is_a($session['user'], 'Member')) {
         foreach ($user as $key => $val) {
             $this->template->setVar('user_' . $key, $val);
         }
     }
     /* Set the number of queries */
     $template->setVar('num_queries', $_DBA->num_queries);
     /* Set the Load time */
     $template->setVar('load_time', $this->timer->__toString());
     if (DEBUG_SQL) {
         $debug_url =& new Url($_URL->__toString());
         $debug_url->args['debug'] = 1;
         $template->setVar('debug_url', $debug_url->__toString());
         $template->show('sql_debug');
         if (isset($request['debug']) && $request['debug'] == 1) {
             /* Output our debugged SQL */
             debug_sql();
         }
     }
     /* Do the mail queue */
     execute_mail_queue();
     /* Do the topic queue */
     execute_topic_queue();
     /**
      * Render the template 
      */
     error::reset();
     $template->Render();
     if (error::grab()) {
         critical_error();
     }
 }
Пример #13
0
function compile_error($message, $file, $line)
{
    error::reset();
    error::pitch(new FAError($message, $file, $line));
    critical_error();
}
Пример #14
0
    /**
     * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
     *
     * @param  boolean		Whether to create a persistant connection
     * @param  string			The database name
     * @param  string			The database host (the server)
     * @param  string			The database connection username
     * @param  string			The database connection password
     * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
     * @return ?array			A database connection (NULL: failed)
     */
    function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
    {
        if ($db_host != 'localhost') {
            fatal_exit(do_lang_tempcode('ONLY_LOCAL_HOST_FOR_TYPE'));
        }
        // Potential cacheing
        global $CACHE_DB;
        if (isset($CACHE_DB[$db_name][$db_host])) {
            return $CACHE_DB[$db_name][$db_host];
        }
        $db_name_short = $db_name;
        if (strpos($db_name, '.mdb') !== false) {
            $db_name = '
	DRIVER=Microsoft Access Driver (*.mdb);
	DBQ=' . $db_name . ';
	UserCommitSync=Yes;
	Threads=3;
	SafeTransactions=0;
	PageTimeout=5;
	MaxScanRows=8;
	MaxBufferSize=2048;
	DriverId=281;
	DefaultDir=C:/ProgramFiles/CommonFiles/ODBC/DataSources';
        }
        if (!function_exists('odbc_connect')) {
            $error = 'The ODBC PHP extension not installed (anymore?). You need to contact the system administrator of this server.';
            if ($fail_ok) {
                echo $error;
                return NULL;
            }
            critical_error('PASSON', $error);
        }
        $db = $persistent ? @odbc_pconnect($db_name, $db_user, $db_password) : @odbc_connect($db_name, $db_user, $db_password);
        if ($db === false) {
            $error = 'Could not connect to database-server (' . odbc_errormsg() . ')';
            if ($fail_ok) {
                echo $error;
                return NULL;
            }
            critical_error('PASSON', $error);
            //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
        }
        if (!$db) {
            fatal_exit(do_lang('CONNECT_DB_ERROR'));
        }
        $CACHE_DB[$db_name_short][$db_host] = $db;
        return $db;
    }
Пример #15
0
/**
 * This function is a very important one when coding. It allows you to include a source code file (from root/sources/ or root/sources_custom/) through the proper channels.
 * You should remember this function, and not substitute anything else for it, as that will likely make your code unstable.
 * It is key to source code modularity in ocPortal.
 *
 * @param  string			The codename for the source module to load (or a full relative path, ending with .php; if custom checking is needed, this must be the custom version)
 * @param  boolean		Whether to cleanly fail when a source file is missing
 */
function require_code($codename, $light_exit = false)
{
    $hphp = defined('HIPHOP_PHP');
    if ($hphp) {
        if ($codename == 'tempcode') {
            $codename = 'tempcode__runtime';
        }
        if ($codename == 'tempcode_compiler') {
            $codename = 'tempcode_compiler__runtime';
        }
    }
    global $_REQUIRED_CODE, $FILE_BASE, $SITE_INFO;
    if (isset($_REQUIRED_CODE[$codename])) {
        return;
    }
    $_REQUIRED_CODE[$codename] = 1;
    $shorthand = strpos($codename, '.php') === false;
    if (!$shorthand) {
        $non_custom_codename = str_replace('_custom/', '/', $codename);
        $_REQUIRED_CODE[$non_custom_codename] = 1;
    }
    $codename = filter_naughty($codename);
    static $mue = NULL;
    if ($mue === NULL) {
        $mue = function_exists('memory_get_usage');
    }
    if ($mue && isset($_GET['keep_show_loading']) && $_GET['keep_show_loading'] == '1') {
        if (function_exists('memory_get_usage')) {
            $before = memory_get_usage();
        }
    }
    $worked = false;
    $path_a = $FILE_BASE . '/' . ($shorthand ? 'sources_custom/' . $codename . '.php' : $codename);
    $path_b = $FILE_BASE . '/' . ($shorthand ? 'sources/' . $codename . '.php' : $non_custom_codename);
    $has_original = NULL;
    if (isset($GLOBALS['MEM_CACHE'])) {
        global $CODE_OVERRIDES;
        if (!isset($CODE_OVERRIDES)) {
            $CODE_OVERRIDES = persistant_cache_get('CODE_OVERRIDES');
            if ($CODE_OVERRIDES === NULL) {
                $CODE_OVERRIDES = array();
            }
        }
        if (isset($CODE_OVERRIDES[$codename])) {
            $has_override = $CODE_OVERRIDES[$codename];
            $has_original = $CODE_OVERRIDES['!' . $codename];
        } else {
            $has_override = is_file($path_a);
            $has_original = is_file($path_b);
            $CODE_OVERRIDES[$codename] = $has_override;
            $CODE_OVERRIDES['!' . $codename] = $has_original;
            persistant_cache_set('CODE_OVERRIDES', $CODE_OVERRIDES, true);
        }
    } else {
        $has_override = is_file($path_a);
    }
    if (isset($SITE_INFO['safe_mode']) && $SITE_INFO['safe_mode'] == '1') {
        $has_override = false;
    }
    if ($has_override && (!function_exists('in_safe_mode') || !in_safe_mode() || !is_file($path_b))) {
        $done_init = false;
        $init_func = 'init__' . str_replace('/', '__', str_replace('.php', '', $codename));
        if (!isset($has_original)) {
            $has_original = is_file($path_b);
        }
        if ($path_a != $path_b && $has_original) {
            $orig = str_replace(array('?' . '>', '<?php'), array('', ''), file_get_contents($path_b));
            $a = file_get_contents($path_a);
            if ((strpos($codename, '.php') === false || strpos($a, 'class Mx_') === false) && (function_exists('quercus_version') || !$hphp)) {
                $functions_before = get_defined_functions();
                $classes_before = get_declared_classes();
                include $path_a;
                // Include our overrride
                $functions_after = get_defined_functions();
                $classes_after = get_declared_classes();
                $functions_diff = array_diff($functions_after['user'], $functions_before['user']);
                // Our override defined these functions
                $classes_diff = array_diff($classes_after, $classes_before);
                $pure = true;
                // We will set this to false if it does not have all functions the main one has. If it does have all functions we know we should not run the original init, as it will almost certainly just have been the same code copy&pasted through.
                $overlaps = false;
                foreach ($functions_diff as $function) {
                    if (strpos($orig, 'function ' . $function . '(') !== false) {
                        $orig = str_replace('function ' . $function . '(', 'function non_overrided__' . $function . '(', $orig);
                        $overlaps = true;
                    } else {
                        $pure = false;
                    }
                }
                foreach ($classes_diff as $class) {
                    if (substr(strtolower($class), 0, 6) == 'module') {
                        $class = ucfirst($class);
                    }
                    if (substr(strtolower($class), 0, 4) == 'hook') {
                        $class = ucfirst($class);
                    }
                    if (strpos($orig, 'class ' . $class) !== false) {
                        $orig = str_replace('class ' . $class, 'class non_overrided__' . $class, $orig);
                        $overlaps = true;
                    } else {
                        $pure = false;
                    }
                }
                // See if we can get away with loading init function early. If we can we do a special version of it that supports fancy code modification. Our override isn't allowed to call the non-overridden init function as it won't have been loaded up by PHP in time. Instead though we will call it ourselves if it still exists (hasn't been removed by our own init function) because it likely serves a different purpose to our code-modification init function and copy&paste coding is bad.
                $doing_code_modifier_init = function_exists($init_func);
                if ($doing_code_modifier_init) {
                    $test = call_user_func_array($init_func, array($orig));
                    if (is_string($test)) {
                        $orig = $test;
                    }
                    $done_init = true;
                }
                if (!$doing_code_modifier_init && !$overlaps) {
                    include $path_b;
                } else {
                    eval($orig);
                    // Load up modified original
                }
                if (!$pure && $doing_code_modifier_init && function_exists('non_overrided__init__' . str_replace('/', '__', str_replace('.php', '', $codename)))) {
                    call_user_func('non_overrided__init__' . str_replace('/', '__', str_replace('.php', '', $codename)));
                }
            } else {
                // Note we load the original and then the override. This is so function_exists can be used in the overrides (as we can't support the re-definition) OR in the case of Mx_ class derivation, so that the base class is loaded first.
                if (isset($_GET['keep_show_parse_errors']) && (function_exists('quercus_version') || !$hphp)) {
                    @ini_set('display_errors', '0');
                    $orig = str_replace('?' . '>', '', str_replace('<?php', '', file_get_contents($path_b)));
                    if (eval($orig) === false) {
                        if (!function_exists('fatal_exit') || $codename == 'failure') {
                            critical_error('PASSON', @strval($php_errormsg) . ' [sources/' . $codename . '.php]');
                        }
                        fatal_exit(@strval($php_errormsg) . ' [sources/' . $codename . '.php]');
                    }
                } else {
                    include $path_b;
                }
                if (isset($_GET['keep_show_parse_errors']) && (function_exists('quercus_version') || !$hphp)) {
                    @ini_set('display_errors', '0');
                    $orig = str_replace('?' . '>', '', str_replace('<?php', '', file_get_contents($path_a)));
                    if (eval($orig) === false) {
                        if (!function_exists('fatal_exit') || $codename == 'failure') {
                            critical_error('PASSON', @strval($php_errormsg) . ' [sources_custom/' . $codename . '.php]');
                        }
                        fatal_exit(@strval($php_errormsg) . ' [sources_custom/' . $codename . '.php]');
                    }
                } else {
                    include $path_a;
                }
            }
        } else {
            if (isset($_GET['keep_show_parse_errors']) && (function_exists('quercus_version') || !$hphp)) {
                @ini_set('display_errors', '0');
                $orig = str_replace('?' . '>', '', str_replace('<?php', '', file_get_contents($path_a)));
                if (eval($orig) === false) {
                    if (!function_exists('fatal_exit') || $codename == 'failure') {
                        critical_error('PASSON', @strval($php_errormsg) . ' [sources_custom/' . $codename . '.php]');
                    }
                    fatal_exit(@strval($php_errormsg) . ' [sources_custom/' . $codename . '.php]');
                }
            } else {
                include $path_a;
            }
        }
        if ($mue && isset($_GET['keep_show_loading']) && $_GET['keep_show_loading'] == '1') {
            if (function_exists('memory_get_usage')) {
                print '<!-- require_code: ' . htmlentities($codename) . ' (' . number_format(memory_get_usage() - $before) . ' bytes used, now at ' . number_format(memory_get_usage()) . ') -->' . "\n";
                flush();
            }
        }
        if (!$done_init) {
            if (function_exists($init_func)) {
                call_user_func($init_func);
            }
        }
        $worked = true;
    } else {
        if (isset($_GET['keep_show_parse_errors']) && (function_exists('quercus_version') || !$hphp)) {
            $contents = @file_get_contents($path_b);
            if ($contents !== false) {
                @ini_set('display_errors', '0');
                $orig = str_replace(array('?' . '>', '<' . '?php'), array('', ''), $contents);
                if (eval($orig) === false) {
                    if (!function_exists('fatal_exit') || $codename == 'failure') {
                        critical_error('PASSON', @strval($php_errormsg) . ' [sources/' . $codename . '.php]');
                    }
                    fatal_exit(@strval($php_errormsg) . ' [sources/' . $codename . '.php]');
                }
                $worked = true;
            }
        } else {
            $php_errormsg = '';
            @(include $path_b);
            if ($php_errormsg == '') {
                $worked = true;
            }
        }
        if ($worked) {
            if ($mue && isset($_GET['keep_show_loading']) && $_GET['keep_show_loading'] == '1') {
                if (function_exists('memory_get_usage')) {
                    print '<!-- require_code: ' . htmlentities($codename) . ' (' . number_format(memory_get_usage() - $before) . ' bytes used, now at ' . number_format(memory_get_usage()) . ') -->' . "\n";
                    flush();
                }
            }
            $init_func = 'init__' . str_replace(array('/', '.php'), array('__', ''), $codename);
            if (function_exists($init_func)) {
                call_user_func($init_func);
            }
        }
    }
    if ($worked) {
        return;
    }
    if ($light_exit) {
        warn_exit(do_lang_tempcode('MISSING_SOURCE_FILE', escape_html($codename), escape_html($path_b)));
    }
    if (!function_exists('do_lang')) {
        if ($codename == 'critical_errors') {
            exit('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . chr(10) . '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"><head><title>Critical startup error</title></head><body><h1>ocPortal startup error</h1><p>The ocPortal critical error message file, sources/critical_errors.php, could not be located. This is almost always due to an incomplete upload of the ocPortal system, so please check all files are uploaded correctly.</p><p>Once all ocPortal files are in place, ocPortal must actually be installed by running the installer. You must be seeing this message either because your system has become corrupt since installation, or because you have uploaded some but not all files from our manual installer package: the quick installer is easier, so you might consider using that instead.</p><p>ocProducts maintains full documentation for all procedures and tools, especially those for installation. These may be found on the <a href="http://ocportal.com">ocPortal website</a>. If you are unable to easily solve this problem, we may be contacted from our website and can help resolve it for you.</p><hr /><p style="font-size: 0.8em">ocPortal is a website engine created by ocProducts.</p></body></html>');
            require $GLOBALS['FILE_BASE'] . '/sources/global.php';
        }
        critical_error('MISSING_SOURCE', $codename);
    }
    fatal_exit(do_lang_tempcode('MISSING_SOURCE_FILE', escape_html($codename), escape_html($path_b)));
}
Пример #16
0
/**
 * Echo an error message, and a debug back-trace of the current execution stack. Use this for debugging purposes.
 *
 * @param  string			An error message
 */
function die_html_trace($message)
{
    if (!function_exists('debug_backtrace')) {
        critical_error('EMERGENCY', $message);
    }
    if (!function_exists('var_export')) {
        critical_error('EMERGENCY', $message);
    }
    //$x=@ob_get_contents(); @ob_end_clean(); //if (is_string($x)) @print($x);	Disabled as causes weird crashes
    $_trace = debug_backtrace();
    $trace = '<div class="medborder medborder_box"><h2>Stack trace&hellip;</h2>';
    foreach ($_trace as $stage) {
        $traces = '';
        foreach ($stage as $key => $value) {
            if (is_object($value) && is_a($value, 'ocp_tempcode') || is_null($value) || is_array($value) && strlen(serialize($value)) > MAX_STACK_TRACE_VALUE_LENGTH) {
                $_value = gettype($value);
            } else {
                @ob_start();
                /*var_dump*/
                var_export($value);
                $_value = ob_get_contents();
                ob_end_clean();
            }
            global $SITE_INFO;
            if (is_object($_value)) {
                $_value = $_value->evaluate();
            }
            if (isset($SITE_INFO['db_site_password']) && strlen($SITE_INFO['db_site_password']) > 4) {
                $_value = str_replace($SITE_INFO['db_site_password'], '(password removed)', $_value);
            }
            if (isset($SITE_INFO['db_forums_password']) && strlen($SITE_INFO['db_forums_password']) > 4) {
                $_value = str_replace($SITE_INFO['db_forums_password'], '(password removed)', $_value);
            }
            $traces .= ucfirst($key) . ' -> ' . escape_html($_value) . '<br />' . chr(10);
        }
        $trace .= '<p>' . $traces . '</p>' . chr(10);
    }
    $trace .= '</div>';
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($trace);
    }
    critical_error('EMERGENCY', $message . $trace);
}
Пример #17
0
/**
 * ocPortal error handler (hooked into PHP error system).
 *
 * @param  integer		The error code-number
 * @param  PATH			The error message
 * @param  string			The file the error occurred in
 * @param  integer		The line the error occurred on
 * @return boolean		Always false
 */
function ocportal_error_handler($errno, $errstr, $errfile, $errline)
{
    if (error_reporting() == 0 && !$GLOBALS['DYING_BADLY']) {
        return false;
    }
    // This actually tells if @ was used oddly enough. You wouldn't figure from the PHP docs.
    if (error_reporting() & $errno || $GLOBALS['DYING_BADLY']) {
        // Strip down path for security
        if (substr(str_replace(DIRECTORY_SEPARATOR, '/', $errfile), 0, strlen(get_file_base() . '/')) == str_replace(DIRECTORY_SEPARATOR, '/', get_file_base() . '/')) {
            $errfile = substr($errfile, strlen(get_file_base() . '/'));
        }
        // Work out the error type
        if (!defined('E_RECOVERABLE_ERROR')) {
            define('E_RECOVERABLE_ERROR', 4096);
        }
        switch ($errno) {
            case E_RECOVERABLE_ERROR:
                // constant not defined in all php versions but we defined it
            // constant not defined in all php versions but we defined it
            case E_USER_ERROR:
            case E_PARSE:
            case E_CORE_ERROR:
            case E_COMPILE_ERROR:
            case E_ERROR:
                $type = 'error';
                break;
            case -123:
                // Hacked in for the memtrack extension, which was buggy
            // Hacked in for the memtrack extension, which was buggy
            case E_CORE_WARNING:
            case E_COMPILE_WARNING:
            case E_USER_WARNING:
            case E_WARNING:
                $type = 'warning';
                break;
                //case E_STRICT: (constant not defined in all php versions)
                //case E_DEPRECATED: (constant not defined in all php versions)
                //case E_USER_DEPRECATED: (constant not defined in all php versions)
            //case E_STRICT: (constant not defined in all php versions)
            //case E_DEPRECATED: (constant not defined in all php versions)
            //case E_USER_DEPRECATED: (constant not defined in all php versions)
            case E_USER_NOTICE:
            case E_NOTICE:
                $type = 'notice';
                break;
            default:
                // We don't know the error type so it's probably best to continue (could be a problem with something getting deprecated)
                return false;
        }
        $GLOBALS['DYING_BADLY'] = false;
        // So error suppress works again
        if (strpos($errstr, 'Allowed memory') !== false) {
            global $_REQUIRED_CODE;
            if (!array_key_exists('failure', $_REQUIRED_CODE)) {
                @error_log('PHP ' . ucwords($type) . ':  ' . $errstr . ' in ' . $errfile . ' on line ' . strval($errline) . ' @ ' . get_self_url_easy(), 0);
                // We really want to know the URL where this is happening (normal PHP error logging does not include it)!
                critical_error('EMERGENCY', $errstr . escape_html(' [' . $errfile . ' at ' . strval($errline) . ']'));
            }
        }
        require_code('failure');
        _ocportal_error_handler($type, $errno, $errstr, $errfile, $errline);
    }
    return false;
}
Пример #18
0
 /**
  * Read in all the records from a table.
  *
  * @param  array			Database connection
  * @param  string			The table name
  * @param  string			What the table will be renamed to (blank: N/A)
  * @param  ?array			Schema to type-set against (NULL: do not do type-setting)
  * @param  ?array			Expression filtering results (used for optimisation, seeing if we can get a quick key match) (NULL: no data to filter with)
  * @param  boolean		Whether to not output an error on some kind of run-time failure (parse errors and clear programming errors are always fatal)
  * @param  string			Query that was executed
  * @param  boolean		Whether to include fields that are present in the actual records but not in our schema
  * @return ?array			The collected records (NULL: error)
  */
 function _read_all_records($db, $table_name, $table_as, $schema, $where_expr, $fail_ok, $query, $include_unused_fields = false)
 {
     $records = array();
     $key_fragments = '';
     // We can do a filename substring search to stop us having to parse ALL
     $must_contain = NULL;
     if (!is_null($schema) && !is_null($where_expr)) {
         $keys = array();
         foreach ($schema as $key => $type) {
             if (strpos($type, '*') !== false) {
                 $keys[] = $key;
             }
         }
         foreach ($keys as $i => $key) {
             if (strpos($key, '.') !== false) {
                 if (substr($key, 0, strpos($key, '.')) == $table_as) {
                     $key = substr($key, strpos($key, '.') + 1);
                 } else {
                     continue;
                 }
             }
             $keys[$i] = $key;
         }
         $keys = array_unique($keys);
         $key_lookup = true;
         $where_expr_compressed = $this->_turn_where_expr_to_map($where_expr, $table_as, $schema);
         $where_expr_compressed_b = $this->_turn_where_expr_to_map($where_expr, $table_as, $schema, true);
         $must_contain = array();
         foreach ($where_expr_compressed_b as $key => $val) {
             $new_val = mixed();
             if (is_string($val)) {
                 $new_val = $val;
             } elseif (is_integer($val)) {
                 $new_val = strval($val);
             } elseif (is_float($val)) {
                 $new_val = float_to_raw_string($val);
             } elseif (is_array($val)) {
                 $new_val = array();
                 foreach ($val as $_val) {
                     if (is_string($_val)) {
                         $new_val[] = $_val;
                     } elseif (is_integer($_val)) {
                         $new_val[] = strval($_val);
                     } elseif (is_float($_val)) {
                         $new_val[] = float_to_raw_string($_val);
                     }
                 }
             } else {
                 $new_val = '';
             }
             $must_contain[$key] = $new_val;
         }
         sort($keys);
         foreach ($keys as $key) {
             if ($key_fragments != '') {
                 $key_fragments .= ',';
             }
             if ($key != 'id') {
                 $key_fragments .= str_replace('#', '\\#', preg_quote($key . '='));
             }
             if (!in_array($key, array_keys($where_expr_compressed))) {
                 $key_lookup = false;
                 $key_fragments .= '.*';
             } else {
                 $val = $where_expr_compressed[$key];
                 $new_val = '';
                 if (is_array($val)) {
                     if (count($val) == 1) {
                         $val = $val[0];
                     } else {
                         $key_lookup = false;
                         $key_fragments .= '(';
                         foreach ($val as $i => $possible) {
                             if ($i != 0) {
                                 $key_fragments .= '|';
                             }
                             if (is_string($possible)) {
                                 $new_val = $possible;
                             } elseif (is_integer($possible)) {
                                 $new_val = strval($possible);
                             } elseif (is_float($possible)) {
                                 $new_val = float_to_raw_string($possible);
                             }
                             $key_fragments .= str_replace('#', '\\#', preg_quote($this->_escape_name($new_val)));
                         }
                         $key_fragments .= ')';
                         continue;
                     }
                 }
                 if (is_string($val)) {
                     $new_val = $val;
                 } elseif (is_integer($val)) {
                     $new_val = strval($val);
                 } elseif (is_float($val)) {
                     $new_val = float_to_raw_string($val);
                 }
                 $key_fragments .= str_replace('#', '\\#', preg_quote($this->_escape_name($new_val)));
             }
         }
         $key_buildup = $this->_guid($schema, $where_expr_compressed);
         if ($key_lookup && $key_buildup != '') {
             $file_exists_xml = file_exists($db[0] . '/' . $table_name . '/' . $key_buildup . '.xml');
             $file_exists_xml_volatile = file_exists($db[0] . '/' . $table_name . '/' . $key_buildup . '.xml-volatile');
             if ($file_exists_xml || $file_exists_xml_volatile) {
                 $the_key = preg_replace('#\\.[\\w\\-]+$#', '', $key_buildup);
                 $suffix = $file_exists_xml ? '.xml' : '.xml-volatile';
                 $records[$the_key] = $this->_read_record($db[0] . '/' . $table_name . '/' . $key_buildup . $suffix, $schema, NULL, $include_unused_fields);
                 if ($table_name == get_table_prefix() . 'translate') {
                     $sup_file = $db[0] . '/' . $table_name . '/sup/' . $key_buildup . '.xml-volatile';
                     if (file_exists($sup_file)) {
                         $sup_record = $this->_read_record($sup_file, $schema, NULL, $include_unused_fields);
                         $records[$the_key]['text_parsed'] = $sup_record['text_parsed'];
                     }
                 }
                 return $records;
             } else {
                 return array();
             }
         }
     }
     global $DIR_CONTENTS_CACHE;
     if (!isset($DIR_CONTENTS_CACHE[$table_name])) {
         if (!file_exists($db[0] . '/' . $table_name)) {
             mkdir($db[0] . '/' . $table_name, 0777);
             require_code('files');
             fix_permissions($db[0] . '/' . $table_name, 0777);
             sync_file($db[0] . '/' . $table_name);
         }
         @chdir($db[0] . '/' . $table_name);
         $dh = @glob('{,.}*.{xml,xml-volatile}', GLOB_NOSORT | GLOB_BRACE);
         if ($dh === false) {
             $dh = array();
         }
         @chdir(get_file_base());
         if (file_exists($db[0] . '/' . $table_name . '/.xml')) {
             $dh[] = '.xml';
         } elseif (file_exists($db[0] . '/' . $table_name . '/.xml-volatile')) {
             $dh[] = '.xml-volatile';
         }
         $DIR_CONTENTS_CACHE[$table_name] = $dh;
     } else {
         $dh = $DIR_CONTENTS_CACHE[$table_name];
     }
     if ($dh === false && $fail_ok) {
         return NULL;
     }
     if ($dh === false) {
         critical_error('PASSON', 'Failure to read table ' . $table_name);
     }
     $regexp = '#^' . $key_fragments . '(' . preg_quote('.xml') . '|' . preg_quote('.xml-volatile') . ')$#';
     foreach ($dh as $file) {
         if ($key_fragments != '') {
             if (preg_match($regexp, $file) == 0) {
                 continue;
             }
         }
         $full_path = $db[0] . '/' . $table_name . '/' . $file;
         if (strlen($full_path) >= 255 && strpos(strtolower(PHP_OS), 'win') !== false) {
             continue;
         }
         // :(
         $read = $this->_read_record($full_path, $schema, $must_contain, $include_unused_fields);
         if (!is_null($read)) {
             $the_key = preg_replace('#\\.[\\w\\-]+$#', '', $file);
             $records[$the_key] = $read;
             if ($table_name == get_table_prefix() . 'translate') {
                 $sup_file = $db[0] . '/' . $table_name . '/sup/' . preg_replace('#\\.\\w+$#', '', $file) . '.xml-volatile';
                 if (file_exists($sup_file)) {
                     $records[$the_key] += $this->_read_record($sup_file, $schema, NULL, $include_unused_fields);
                 }
             }
         }
     }
     return $records;
 }
Пример #19
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (note for mySQL, it's actually a pair, containing the database name too: because we need to select the name before each query on the connection) (NULL: error)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     unset($persistent);
     if (!function_exists('mysqli_connect')) {
         $error = 'mySQLi not on server (anymore?). Try using the \'mysql\' database driver. To use it, edit the info.php config file.';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     // Potential cacheing
     global $CACHE_DB, $LAST_SELECT_DB;
     $x = serialize(array($db_name, $db_host));
     if (array_key_exists($x, $CACHE_DB)) {
         if ($LAST_SELECT_DB[1] != $db_name) {
             mysqli_select_db($CACHE_DB[$x], $db_name);
             $LAST_SELECT_DB = array($CACHE_DB[$x], $db_name);
         }
         return array($CACHE_DB[$x], $db_name);
     }
     $db = @mysqli_connect($db_host, $db_user, $db_password);
     if ($db === false) {
         $error = 'Could not connect to database-server (when authenticating) (' . mysqli_connect_error() . ')';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
     }
     if (!mysqli_select_db($db, $db_name)) {
         if ($db_user == 'root') {
             @mysqli_query($db, 'CREATE DATABASE IF NOT EXISTS ' . $db_name);
         }
         if (!mysqli_select_db($db, $db_name)) {
             $error = 'Could not connect to database (' . mysqli_error($db) . ')';
             if ($fail_ok) {
                 echo $error . chr(10);
                 return NULL;
             }
             critical_error('PASSON', $error);
             //warn_exit(do_lang_tempcode('CONNECT_ERROR'));
         }
     }
     $LAST_SELECT_DB = array($db, $db_name);
     /*	$mysql_version=mysqli_get_server_info($db);
     		if (($mysql_version[0]=='3') && (!file_exists(get_file_base().'/old_mysql'))) exit('The mySQL version used is too old (Version '.$mysql_version.' used, whilst at least Version 4.0 is required)');*/
     $CACHE_DB[$x] = $db;
     global $SITE_INFO;
     if (!array_key_exists('database_charset', $SITE_INFO)) {
         $SITE_INFO['database_charset'] = strtolower(get_charset()) == 'utf-8' ? 'utf8' : 'latin1';
     }
     if (function_exists('mysqli_set_charset')) {
         mysqli_set_charset($db, $SITE_INFO['database_charset']);
     } else {
         @mysqli_query($db, 'SET NAMES "' . addslashes($SITE_INFO['database_charset']) . '"');
     }
     @mysqli_query($db, 'SET WAIT_TIMEOUT=28800');
     @mysqli_query($db, 'SET SQL_BIG_SELECTS=1');
     if (get_forum_type() == 'ocf' && $GLOBALS['IN_MINIKERNEL_VERSION'] == 0) {
         @mysqli_query($db, 'SET sql_mode=STRICT_ALL_TABLES');
     }
     // NB: Can add ,ONLY_FULL_GROUP_BY for testing on what other DBs will do, but can_arbitrary_groupby() would need to be made to return false
     return array($db, $db_name);
 }
Пример #20
0
/**
 * This is a less-revealing alternative to fatal_exit, that is used for user-errors/common-corruption-scenarios
 *
 * @param  mixed			The error message
 */
function warn_exit($text)
{
    // To break any looping of errors
    global $EXITING;
    if (!is_null($EXITING) || !class_exists('ocp_tempcode')) {
        if (get_domain() == 'localhost' || function_exists('get_member') && has_specific_permission(get_member(), 'see_stack_dump')) {
            die_html_trace($text);
        } else {
            critical_error('RELAY', is_object($text) ? $text->evaluate() : escape_html($text));
        }
    }
    $EXITING = 1;
    $title = get_page_title('ERROR_OCCURRED');
    $echo = new ocp_tempcode();
    $echo->attach(do_template('WARN_SCREEN', array('TITLE' => $title, 'TEXT' => $text, 'PROVIDE_BACK' => false)));
    $css_url = 'install.php?type=css';
    $css_url_2 = 'install.php?type=css_2';
    $logo_url = 'install.php?type=logo';
    $version = strval(ocp_version());
    $version .= (is_numeric(ocp_version_minor()) ? '.' : ' ') . ocp_version_minor();
    if (!array_key_exists('step', $_GET)) {
        $_GET['step'] = 1;
    }
    require_code('tempcode_compiler');
    $css_nocache = _do_template('default', '/css/', 'no_cache', 'no_cache', 'EN', '.css');
    $out_final = do_template('INSTALLER_WRAP', array('CSS_NOCACHE' => $css_nocache, 'DEFAULT_FORUM' => '', 'PASSWORD_PROMPT' => '', 'CSS_URL' => $css_url, 'CSS_URL_2' => $css_url_2, 'LOGO_URL' => $logo_url, 'STEP' => integer_format(intval($_GET['step'])), 'CONTENT' => $echo, 'VERSION' => $version));
    $out_final->evaluate_echo();
    exit;
}
Пример #21
0
/**
 * A template has not been structurally cached, so compile it and store in the cache.
 *
 * @param  ID_TEXT			The theme the template is in the context of
 * @param  PATH				The path to the template file
 * @param  ID_TEXT			The codename of the template (e.g. foo)
 * @param  ID_TEXT			The actual codename to use for the template (e.g. foo_mobile)
 * @param  LANGUAGE_NAME	The language the template is in the context of
 * @param  string				File type suffix of template file (e.g. .tpl)
 * @param  ?ID_TEXT			The theme to cache in (NULL: main theme)
 * @return tempcode			The compiled tempcode
 */
function _do_template($theme, $path, $codename, $_codename, $lang, $suffix, $theme_orig = NULL)
{
    if (is_null($theme_orig)) {
        $theme_orig = $theme;
    }
    if (is_null($GLOBALS['CURRENT_SHARE_USER'])) {
        $base_dir = ($theme == 'default' && ($suffix != '.css' || strpos($path, '/css_custom') === false) ? get_file_base() : get_custom_file_base()) . '/themes/';
    } else {
        $base_dir = get_custom_file_base() . '/themes/';
        if (!is_file($base_dir . $theme . $path . $codename . $suffix)) {
            $base_dir = get_file_base() . '/themes/';
        }
    }
    global $CACHE_TEMPLATES, $FILE_ARRAY, $TEMPLATE_PREVIEW_OP, $MEM_CACHE;
    if (isset($FILE_ARRAY)) {
        $html = unixify_line_format(file_array_get('themes/' . $theme . $path . $codename . $suffix));
    } else {
        $html = unixify_line_format(file_get_contents($base_dir . filter_naughty($theme . $path . $codename) . $suffix, FILE_TEXT));
    }
    if ($GLOBALS['SEMI_DEBUG_MODE'] && strpos($html, '.innerHTML') !== false && !running_script('install') && strpos($html, 'Parser hint: .innerHTML okay') === false) {
        attach_message('Do not use the .innerHTML property in your Javascript because it will not work in true XHTML (when the browsers real XML parser is in action). Use ocPortal\'s global setInnerHTML/getInnerHTML functions.', 'warn');
    }
    // Strip off trailing final lines from single lines templates. Editors often put these in, and it causes annoying "visible space" issues
    if (substr($html, -1, 1) == chr(10) && substr_count($html, chr(10)) == 1) {
        $html = substr($html, 0, strlen($html) - 1);
    }
    if ($TEMPLATE_PREVIEW_OP) {
        $test = post_param($codename, NULL);
        if (!is_null($test)) {
            $html = post_param($test . '_new');
        }
    }
    $result = template_to_tempcode($html, 0, false, $suffix != '.tpl' ? '' : $codename, $theme_orig, $lang);
    if ($CACHE_TEMPLATES && !$TEMPLATE_PREVIEW_OP && ($suffix == '.tpl' || $codename == 'no_cache')) {
        $path2 = get_custom_file_base() . '/themes/' . $theme_orig . '/templates_cached/' . filter_naughty($lang) . '/';
        $myfile = @fopen($path2 . filter_naughty($_codename) . $suffix . '.tcp', 'wb');
        if ($myfile === false) {
            @mkdir(dirname($path2), 0777);
            fix_permissions(dirname($path2), 0777);
            sync_file(dirname($path2));
            if (@mkdir($path2, 0777)) {
                fix_permissions($path2, 0777);
                sync_file($path2);
            } else {
                if ($codename == 'SCREEN_TITLE') {
                    critical_error('PASSON', do_lang('WRITE_ERROR', escape_html($path2 . filter_naughty($_codename) . $suffix . '.tcp')));
                }
                // Bail out hard if would cause a loop
                intelligent_write_error($path2 . filter_naughty($_codename) . $suffix . '.tcp');
            }
        } else {
            $data_to_write = '<' . '?php' . chr(10) . $result->to_assembly($lang) . chr(10) . '?' . '>';
            if (fwrite($myfile, $data_to_write) >= strlen($data_to_write)) {
                // Success
                fclose($myfile);
                require_code('files');
                fix_permissions($path2 . filter_naughty($_codename) . $suffix . '.tcp');
            } else {
                // Failure
                fclose($myfile);
                @unlink($path2 . filter_naughty($_codename) . $suffix . '.tcp');
                // Can't leave this around, would cause problems
            }
        }
    }
    return $result;
}
/**
 * Filter a member ID through SU, if SU is on and if the user has permission.
 *
 * @param  MEMBER			Real logged in member
 * @return MEMBER			Simulated member
 */
function try_su_login($member)
{
    $ks = get_param('keep_su', '');
    require_code('permissions');
    if (method_exists($GLOBALS['FORUM_DRIVER'], 'forum_layer_initialise')) {
        $GLOBALS['FORUM_DRIVER']->forum_layer_initialise();
    }
    if (has_specific_permission($member, 'assume_any_member')) {
        $su = $GLOBALS['FORUM_DRIVER']->get_member_from_username($ks);
        if (is_null($su) && is_numeric($ks)) {
            $su = intval($ks);
        }
        if (is_null($su)) {
            require_code('site');
            attach_message(do_lang_tempcode('_USER_NO_EXIST', escape_html($ks)), 'warn');
            return get_member();
        }
        if (!$GLOBALS['FORUM_DRIVER']->is_super_admin($su) || $GLOBALS['FORUM_DRIVER']->is_super_admin($member)) {
            if (!is_null($su)) {
                $member = $su;
            } elseif (is_numeric($ks)) {
                $member = intval($ks);
            }
            if (!is_guest($member) && $GLOBALS['FORUM_DRIVER']->is_banned($member)) {
                global $CACHED_THEME;
                $CACHED_THEME = 'default';
                critical_error('MEMBER_BANNED');
            }
        }
        $GLOBALS['IS_ACTUALLY_ADMIN'] = true;
    }
    return $member;
}
Пример #23
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (NULL: failed)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     // Potential cacheing
     global $CACHE_DB;
     if (isset($CACHE_DB[$db_name][$db_host])) {
         return $CACHE_DB[$db_name][$db_host];
     }
     if (!function_exists('sqlite_popen')) {
         $error = 'The sqlite PHP extension not installed (anymore?). You need to contact the system administrator of this server.';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     $error_message = '';
     $db = $persistent ? @sqlite_popen(get_file_base() . '/' . $db_name, 0666, $error_message) : @sqlite_open(get_file_base() . '/' . $db_name, 0666, $error_message);
     if ($db === false) {
         $error = 'Could not open database file (' . $error_message . ')';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
     }
     sqlite_query($db, 'BEGIN TRANSACTION');
     if (!$db) {
         fatal_exit(do_lang('CONNECT_DB_ERROR'));
     }
     $CACHE_DB[$db_name][$db_host] = $db;
     return $db;
 }
Пример #24
0
/**
 * Check disk space usage against page view ratio for shared hosting.
 *
 * @param  integer		The extra space in bytes requested
 */
function check_shared_space_usage($extra)
{
    global $SITE_INFO;
    if (array_key_exists('throttle_space_registered', $SITE_INFO)) {
        $views_till_now = intval(get_value('page_views'));
        $bandwidth_allowed = $SITE_INFO['throttle_space_registered'];
        $total_space = get_directory_size(get_custom_file_base() . '/uploads');
        if ($bandwidth_allowed * 1024 * 1024 >= $total_space + $extra) {
            return;
        }
    }
    if (array_key_exists('throttle_space_complementary', $SITE_INFO)) {
        //		$timestamp_start=$SITE_INFO['custom_user_'].current_share_user();
        //		$days_till_now=(time()-$timestamp_start)/(24*60*60);
        $views_till_now = intval(get_value('page_views'));
        $space_allowed = $SITE_INFO['throttle_space_complementary'] + $SITE_INFO['throttle_space_views_per_meg'] * $views_till_now;
        $total_space = get_directory_size(get_custom_file_base() . '/uploads');
        if ($space_allowed * 1024 * 1024 < $total_space + $extra) {
            critical_error('RELAY', 'The hosted user has exceeded their shared-hosting "disk-space to page-view" ratio. More pages must be viewed before this may be uploaded.');
        }
    }
}
Пример #25
0
/**
 * Get the number of users on the site in the last 5 minutes. The function also maintains the statistic via the sessions table.
 *
 * @return integer		The number of users on the site
 */
function get_num_users_site()
{
    global $NUM_USERS_SITE, $PEAK_USERS_EVER;
    $users_online_time_seconds = 60 * intval(get_option('users_online_time'));
    $NUM_USERS_SITE = get_value_newer_than('users_online', time() - $users_online_time_seconds / 2);
    if ($NUM_USERS_SITE === NULL) {
        $NUM_USERS_SITE = get_value('users_online');
        $count = 0;
        get_online_members(false, NULL, $count);
        if (strval($count) != $NUM_USERS_SITE) {
            $NUM_USERS_SITE = strval($count);
            set_value('users_online', $NUM_USERS_SITE);
        }
    }
    if (intval($NUM_USERS_SITE) > intval(get_option('maximum_users')) && intval(get_option('maximum_users')) > 1 && get_page_name() != 'login' && !has_specific_permission(get_member(), 'access_overrun_site') && !running_script('cron_bridge')) {
        $GLOBALS['HTTP_STATUS_CODE'] = '503';
        header('HTTP/1.0 503 Service Unavailable');
        critical_error('BUSY', do_lang('TOO_MANY_USERS'));
    }
    if (addon_installed('stats')) {
        $PEAK_USERS_EVER = get_value_newer_than('user_peak', time() - $users_online_time_seconds * 10);
        if ($PEAK_USERS_EVER === NULL || $PEAK_USERS_EVER == '') {
            $_peak_users_user = $GLOBALS['SITE_DB']->query_value_null_ok('usersonline_track', 'MAX(peak)', NULL, '', true);
            $PEAK_USERS_EVER = $_peak_users_user === NULL ? $NUM_USERS_SITE : strval($_peak_users_user);
            set_value('user_peak', $PEAK_USERS_EVER);
        }
        if ($NUM_USERS_SITE > $PEAK_USERS_EVER) {
            // In case the record is beaten more than once within the same second
            $time = time();
            $GLOBALS['SITE_DB']->query_delete('usersonline_track', array('date_and_time' => $time), '', 1, NULL, true);
            // New record
            $GLOBALS['SITE_DB']->query_insert('usersonline_track', array('date_and_time' => $time, 'peak' => intval($NUM_USERS_SITE)), false, true);
        }
    }
    return intval($NUM_USERS_SITE);
}
Пример #26
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (NULL: failed)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     // Potential cacheing
     global $CACHE_DB;
     if (isset($CACHE_DB[$db_name][$db_host])) {
         return $CACHE_DB[$db_name][$db_host];
     }
     if (!function_exists('sqlsrv_connect') && !function_exists('mssql_pconnect')) {
         $error = 'The sqlserver PHP extension not installed (anymore?). You need to contact the system administrator of this server.';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     if (function_exists('sqlsrv_connect')) {
         if ($db_host == '127.0.0.1' || $db_host == 'localhost') {
             $db_host = '(local)';
         }
         $db = @sqlsrv_connect($db_host, $db_user == '' ? array('Database' => $db_name) : array('UID' => $db_user, 'PWD' => $db_password, 'Database' => $db_name));
     } else {
         $db = $persistent ? @mssql_pconnect($db_host, $db_user, $db_password) : @mssql_connect($db_host, $db_user, $db_password);
     }
     if ($db === false) {
         $error = 'Could not connect to database-server (' . @strval($php_errormsg) . ')';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
     }
     if (!function_exists('sqlsrv_connect')) {
         if (!mssql_select_db($db_name, $db)) {
             $error = 'Could not connect to database (' . mssql_get_last_message() . ')';
             if ($fail_ok) {
                 echo $error;
                 return NULL;
             }
             critical_error('PASSON', $error);
             //warn_exit(do_lang_tempcode('CONNECT_ERROR'));
         }
     }
     $CACHE_DB[$db_name][$db_host] = $db;
     return $db;
 }
Пример #27
0
 /**
  * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
  *
  * @param  boolean		Whether to create a persistant connection
  * @param  string			The database name
  * @param  string			The database host (the server)
  * @param  string			The database connection username
  * @param  string			The database connection password
  * @param  boolean		Whether to on error echo an error and return with a NULL, rather than giving a critical error
  * @return ?array			A database connection (NULL: failed)
  */
 function db_get_connection($persistent, $db_name, $db_host, $db_user, $db_password, $fail_ok = false)
 {
     if ($db_host != 'localhost') {
         fatal_exit(do_lang_tempcode('ONLY_LOCAL_HOST_FOR_TYPE'));
     }
     // Potential cacheing
     global $CACHE_DB;
     if (isset($CACHE_DB[$db_name][$db_host])) {
         return $CACHE_DB[$db_name][$db_host];
     }
     if (!function_exists('odbc_connect')) {
         $error = 'The ODBC PHP extension not installed (anymore?). You need to contact the system administrator of this server.';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
     }
     $db = $persistent ? @odbc_pconnect($db_name, $db_user, $db_password) : @odbc_connect($db_name, $db_user, $db_password);
     if ($db === false) {
         $error = 'Could not connect to database-server (' . odbc_errormsg() . ')';
         if ($fail_ok) {
             echo $error;
             return NULL;
         }
         critical_error('PASSON', $error);
         //warn_exit(do_lang_tempcode('CONNECT_DB_ERROR'));
     }
     if (!$db) {
         fatal_exit(do_lang('CONNECT_DB_ERROR'));
     }
     $CACHE_DB[$db_name][$db_host] = $db;
     return $db;
 }
Пример #28
0
 /**
  *  Распределяет выполнение запроса на необходимый тип БД
  *  Заполняет $this->{@link sqls},  $this->{@link time_query},  
  *  $this->{@link AllTimeQueries},  $this->{@link id},  
  *   и, при необходимости, логирует запросы.
  *  Если затребовано, то при некорректном запросе генерирует критическую ошибку.
  *  @access private
  *  @param TYPE $variable Распределяет выполнение запроса на необходимый тип БД
  *  @return mixed 
  */
 function operation($log = true)
 {
     if ($this->sql === null) {
         return;
     }
     $this->sql = (string) @trim($this->sql);
     $this->time_query = $this->_mctime();
     switch ($this->type) {
         case 'mysql':
             $result = $this->MySql($log);
             break;
         default:
             $result = false;
             break;
     }
     if ($result !== false) {
         $this->time_query = round($this->_mctime() - $this->time_query, 4);
         $this->AllTimeQueries += $this->time_query;
         $cur =& $this->sqls[];
         $cur['operation'] = $this->oprt;
         $cur['file'] = $this->file;
         $cur['line'] = $this->line;
         $cur['query'] = $this->sql;
         $cur['time'] = $this->time_query;
         $cur['result'] = sizeof($result);
         $this->id = mysql_insert_id();
         unset($cur);
         $this->_clear();
         return $result;
     }
     if ($this->showerr and $this->show_err) {
         if (preg_match('#^[^\']*? \'(.*?)\' in#', mysql_error(), $filter = null)) {
             $this->sql = str_replace($filter[1], '<b>' . $filter[1] . '</b>', $this->sql);
         }
         $str = '<B>Ошибка DB:</B> <BR><BR>' . mysql_error() . ' <BR><BR> ' . $this->sql . '';
         if (function_exists('critical_error')) {
             critical_error($str, $this->file, $this->line);
         } else {
             die($str);
         }
     }
     return false;
 }
Пример #29
0
 /**
  * Get the human-readable form of a language id, or a language entry from a language INI file.
  *
  * @param  ID_TEXT		The language id
  * @param  ?mixed			The first token [string or tempcode] (replaces {1}) (NULL: none)
  * @param  ?mixed			The second token [string or tempcode] (replaces {2}) (NULL: none)
  * @param  ?mixed			The third token (replaces {3}). May be an array of [of string], to allow any number of additional args (NULL: none)
  * @param  ?LANGUAGE_NAME The language to use (NULL: users language)
  * @param  boolean		Whether to cause ocPortal to exit if the lookup does not succeed
  * @return ?mixed			The human-readable content (NULL: not found). String normally. Tempcode if tempcode parameters.
  */
 function _do_lang($codename, $token1 = NULL, $token2 = NULL, $token3 = NULL, $lang = NULL, $require_result = true)
 {
     $pos = strpos($codename, ':');
     if ($pos !== false) {
         require_lang(substr($codename, 0, $pos));
         $codename = substr($codename, $pos + 1);
     }
     global $LANGUAGE, $USER_LANG_CACHED, $RECORD_LANG_STRINGS, $XSS_DETECT, $PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED;
     if ($RECORD_LANG_STRINGS) {
         global $RECORDED_LANG_STRINGS;
         $RECORDED_LANG_STRINGS[$codename] = 1;
     }
     if ($lang === NULL) {
         $lang = $USER_LANG_CACHED === NULL ? user_lang() : $USER_LANG_CACHED;
     }
     if (!isset($LANGUAGE[$lang][$codename]) && (!array_key_exists($lang, $LANGUAGE) || !array_key_exists($codename, $LANGUAGE[$lang]))) {
         global $PAGE_CACHE_LAZY_LOAD, $PAGE_CACHE_LANGS_REQUESTED, $LANG_REQUESTED_LANG;
         if ($PAGE_CACHE_LAZY_LOAD) {
             $PAGE_CACHE_LAZY_LOAD = false;
             // We can't be lazy any more, but we will keep growing our pool so hopefully CAN be lazy the next time
             foreach ($PAGE_CACHE_LANGS_REQUESTED as $request) {
                 list($that_codename, $that_lang) = $request;
                 unset($LANG_REQUESTED_LANG[$that_lang][$that_codename]);
                 require_lang($that_codename, $that_lang, NULL, true);
             }
             $ret = _do_lang($codename, $token1, $token2, $token3, $lang, $require_result);
             if ($ret === NULL) {
                 $PAGE_CACHE_LANG_LOADED[$lang][$codename] = NULL;
                 if ($GLOBALS['MEM_CACHE'] !== NULL) {
                     persistant_cache_set($PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED);
                 } else {
                     @rewind($PAGE_CACHE_FILE);
                     @ftruncate($PAGE_CACHE_FILE, 0);
                     @fwrite($PAGE_CACHE_FILE, serialize($PAGE_CACHE_LANG_LOADED));
                 }
             }
             return $ret;
         }
         require_all_open_lang_files($lang);
     }
     if ($lang == 'xxx') {
         return 'xxx';
     }
     // Helpful for testing language compliancy. We don't expect to see non x's if we're running this language
     if (!isset($LANGUAGE[$lang][$codename]) && (!array_key_exists($lang, $LANGUAGE) || !array_key_exists($codename, $LANGUAGE[$lang]))) {
         if ($lang != fallback_lang()) {
             $ret = do_lang($codename, $token1, $token2, $token3, fallback_lang(), $require_result);
             if ($codename == 'charset') {
                 switch (strtolower($lang)) {
                     case 'ar':
                     case 'bg':
                     case 'zh-CN':
                     case 'zh-TW':
                     case 'hr':
                     case 'cs':
                     case 'da':
                     case 'nl':
                     case 'fi':
                     case 'fr':
                     case 'de':
                     case 'el':
                     case 'hi':
                     case 'it':
                     case 'ja':
                     case 'ko':
                     case 'pl':
                     case 'pt':
                     case 'ro':
                     case 'ru':
                     case 'es':
                     case 'sv':
                         $ret = 'utf-8';
                         break;
                 }
             } elseif (substr($codename, 0, 3) == 'FC_') {
                 $ret = ocp_mb_substr(trim(do_lang(substr($codename, 3), $token1, $token2, $token3, $lang)), 0, 1);
             } elseif ($codename == 'locale') {
                 $ret = strtolower($lang) . '_' . strtoupper($lang);
             } else {
                 $ret2 = strtolower($codename) != $codename ? google_translate($ret, $lang) : $ret;
                 if ($ret2 != $ret) {
                     $ret = $ret2;
                 }
             }
             if ($PAGE_CACHE_FILE !== NULL) {
                 if (!isset($PAGE_CACHE_LANG_LOADED[$lang][$codename]) && isset($PAGE_CACHE_LANG_LOADED[fallback_lang()][$codename])) {
                     $PAGE_CACHE_LANG_LOADED[$lang][$codename] = $ret;
                     // Will have been cached into fallback_lang() from the nested do_lang call, we need to copy it into our cache bucket for this language
                     if ($GLOBALS['MEM_CACHE'] !== NULL) {
                         persistant_cache_set($PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED);
                     } else {
                         @rewind($PAGE_CACHE_FILE);
                         @ftruncate($PAGE_CACHE_FILE, 0);
                         @fwrite($PAGE_CACHE_FILE, serialize($PAGE_CACHE_LANG_LOADED));
                     }
                 }
             }
             return $ret;
         } else {
             if ($require_result) {
                 global $USER_LANG_LOOP, $REQUIRE_LANG_LOOP;
                 //print_r(debug_backtrace());
                 if ($USER_LANG_LOOP == 1) {
                     critical_error('RELAY', 'Missing language code: ' . escape_html($codename) . '. This language code is required to produce error messages, and thus a critical error was prompted by the non-ability to show less-critical error messages. It is likely the source language files (lang/' . fallback_lang() . '/*.ini) for ocPortal on this website have been corrupted.');
                 }
                 if ($REQUIRE_LANG_LOOP >= 2) {
                     return '';
                 }
                 // Probably failing to load global.ini, so just output with some text missing
                 require_code('view_modes');
                 erase_cached_language();
                 fatal_exit(do_lang_tempcode('MISSING_LANG_ENTRY', escape_html($codename)));
             } else {
                 return NULL;
             }
         }
     }
     if ($PAGE_CACHE_FILE !== NULL) {
         if (!isset($PAGE_CACHE_LANG_LOADED[$lang][$codename])) {
             $PAGE_CACHE_LANG_LOADED[$lang][$codename] = $LANGUAGE[$lang][$codename];
             if ($GLOBALS['MEM_CACHE'] !== NULL) {
                 persistant_cache_set($PAGE_CACHE_FILE, $PAGE_CACHE_LANG_LOADED);
             } else {
                 @rewind($PAGE_CACHE_FILE);
                 @ftruncate($PAGE_CACHE_FILE, 0);
                 @fwrite($PAGE_CACHE_FILE, serialize($PAGE_CACHE_LANG_LOADED));
             }
         }
     }
     // Put in parameters
     static $non_plural_non_vowel = array('1', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z');
     $looked_up = $LANGUAGE[$lang][$codename];
     if ($looked_up === NULL) {
         return NULL;
     }
     // Learning cache pool has told us this string definitely does not exist
     $out = str_replace('\\n', "\n", $looked_up);
     $plural_or_vowel_check = strpos($out, '|') !== false;
     if ($XSS_DETECT) {
         ocp_mark_as_escaped($out);
     }
     if ($token1 !== NULL) {
         if (is_object($token1) && $token2 === NULL || $token2 !== NULL && is_object($token2)) {
             $bits = preg_split('#\\{\\d[^\\}]*\\}#', $out, 2, PREG_SPLIT_OFFSET_CAPTURE);
             $ret = new ocp_tempcode();
             foreach ($bits as $bit) {
                 if ($XSS_DETECT) {
                     ocp_mark_as_escaped($bit[0]);
                 }
                 $at = $bit[1];
                 if ($at != 0) {
                     if ($out[$at - 2] == '1') {
                         $ret->attach($token1);
                     } elseif ($out[$at - 2] == '2') {
                         $ret->attach($token2);
                     } elseif ($plural_or_vowel_check && substr($out[$at - 2], 0, 2) == '1|') {
                         $exploded = explode('|', $out[$at - 2]);
                         $_token = $token1->evaluate();
                         $_token_denum = str_replace(',', '', $_token);
                         $ret->attach(in_array(is_numeric($_token_denum) ? $_token_denum : strtolower(substr($_token, 0, 1)), $non_plural_non_vowel) ? $exploded[1] : $exploded[2]);
                     } elseif ($plural_or_vowel_check && substr($out[$at - 2], 0, 2) == '2|') {
                         $exploded = explode('|', $out[$at - 2]);
                         $_token = $token2->evaluate();
                         $_token_denum = str_replace(',', '', $_token);
                         $ret->attach(in_array(is_numeric($_token_denum) ? $_token_denum : strtolower(substr($_token, 0, 1)), $non_plural_non_vowel) ? $exploded[1] : $exploded[2]);
                     }
                 }
                 $ret->attach($bit[0]);
             }
             return $ret;
         } elseif ($token1 !== NULL) {
             $out = str_replace('{1}', $token1, $out);
             if ($plural_or_vowel_check) {
                 $_token_denum = str_replace(',', '', $token1);
                 $out = preg_replace('#\\{1\\|(.*)\\|(.*)\\}#U', in_array(is_numeric($_token_denum) ? $_token_denum : strtolower(substr($token1, 0, 1)), $non_plural_non_vowel) ? '\\1' : '\\2', $out);
             }
             if ($XSS_DETECT && ocp_is_escaped($token1)) {
                 ocp_mark_as_escaped($out);
             }
         }
         if ($token2 !== NULL) {
             if ($XSS_DETECT) {
                 $escaped = ocp_is_escaped($out);
             }
             $out = str_replace('{2}', $token2, $out);
             if ($plural_or_vowel_check) {
                 $_token_denum = str_replace(',', '', $token1);
                 $out = preg_replace('#\\{2\\|(.*)\\|(.*)\\}#U', in_array(is_numeric($_token_denum) ? $_token_denum : strtolower(substr($token2, 0, 1)), $non_plural_non_vowel) ? '\\1' : '\\2', $out);
             }
             if ($XSS_DETECT && ocp_is_escaped($token2) && $escaped) {
                 ocp_mark_as_escaped($out);
             }
             if ($token3 !== NULL) {
                 $i = 3;
                 if (!is_array($token3)) {
                     $token3 = array($token3);
                 }
                 foreach ($token3 as $token) {
                     if ($XSS_DETECT) {
                         $escaped = ocp_is_escaped($out);
                     }
                     $out = str_replace('{' . strval($i) . '}', $token, $out);
                     if ($plural_or_vowel_check) {
                         $_token_denum = str_replace(',', '', $token);
                         $out = preg_replace('#\\{' . strval($i) . '\\|(.*)\\|(.*)\\}#U', in_array(is_numeric($_token_denum) ? $_token_denum : strtolower(substr($token, 0, 1)), $non_plural_non_vowel) ? '\\1' : '\\2', $out);
                     }
                     if ($XSS_DETECT && ocp_is_escaped($token) && $escaped) {
                         ocp_mark_as_escaped($out);
                     }
                     $i++;
                 }
             }
         }
     }
     return $out;
 }
Пример #30
0
/**
 * Load all config options.
 */
function load_options()
{
    global $OPTIONS;
    $OPTIONS = function_exists('persistant_cache_get') ? persistant_cache_get('OPTIONS') : NULL;
    if (is_array($OPTIONS)) {
        return;
    }
    if (strpos(get_db_type(), 'mysql') !== false) {
        global $SITE_INFO;
        $OPTIONS = $GLOBALS['SITE_DB']->query_select('config c LEFT JOIN ' . $GLOBALS['SITE_DB']->get_table_prefix() . 'translate t ON (c.config_value=t.id AND ' . db_string_equal_to('t.language', array_key_exists('default_lang', $SITE_INFO) ? $SITE_INFO['default_lang'] : 'EN') . ' AND (' . db_string_equal_to('c.the_type', 'transtext') . ' OR ' . db_string_equal_to('c.the_type', 'transline') . '))', array('c.the_name', 'c.config_value', 'c.the_type', 'c.c_set', 't.text_original AS config_value_translated'), array(), '', NULL, NULL, true);
    } else {
        $OPTIONS = $GLOBALS['SITE_DB']->query_select('config', array('the_name', 'config_value', 'the_type', 'c_set'), NULL, '', NULL, NULL, true);
    }
    if ($OPTIONS === NULL) {
        critical_error('DATABASE_FAIL');
    }
    $OPTIONS = list_to_map('the_name', $OPTIONS);
    if (function_exists('persistant_cache_set')) {
        persistant_cache_set('OPTIONS', $OPTIONS);
    }
}