Esempio n. 1
0
/**
 * Top level function to (re)generate a Sitemap (xml file, Google-style).
 */
function sitemaps_build()
{
    $GLOBALS['NO_QUERY_LIMIT'] = true;
    $path = get_custom_file_base() . '/ocp_sitemap.xml';
    if (!file_exists($path)) {
        if (!is_writable_wrap(dirname($path))) {
            warn_exit(do_lang_tempcode('WRITE_ERROR_CREATE', escape_html('/')));
        }
    } else {
        if (!is_writable_wrap($path)) {
            warn_exit(do_lang_tempcode('WRITE_ERROR', escape_html('ocp_sitemap.xml')));
        }
    }
    // Runs via a callback mechanism, so we don't need to load an arbitrary complex structure into memory.
    sitemaps_xml_initialise($path);
    spawn_page_crawl('pagelink_to_sitemapsxml', $GLOBALS['FORUM_DRIVER']->get_guest_id(), NULL, DEPTH__ENTRIES);
    sitemaps_xml_finished();
    // Ping search engines
    if (get_option('auto_submit_sitemap') == '1') {
        $ping = true;
        $base_url = get_base_url();
        $not_local = substr($base_url, 0, 16) != 'http://localhost' && substr($base_url, 0, 16) != 'http://127.0.0.1' && substr($base_url, 0, 15) != 'http://192.168.' && substr($base_url, 0, 10) != 'http://10.';
        if ($ping && get_option('site_closed') == '0' && $not_local) {
            // Submit to search engines
            $services = array('http://www.google.com/webmasters/tools/ping?sitemap=', 'http://submissions.ask.com/ping?sitemap=', 'http://www.bing.com/webmaster/ping.aspx?siteMap=', 'http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=SitemapWriter&url=');
            foreach ($services as $service) {
                http_download_file($service . urlencode(get_custom_base_url() . '/ocp_sitemap.xml'), NULL, false);
            }
        }
    }
}
Esempio n. 2
0
/**
 * Log permission checks to the permission_checks.log file, if it exists.
 *
 * @param  MEMBER         The user checking against
 * @param  ID_TEXT        The function that was called to check a permission
 * @param  array          Parameters to this permission-checking function
 * @param  boolean        Whether the permission was held
 */
function handle_permission_check_logging($member, $op, $params, $result)
{
    global $PERMISSION_CHECK_LOGGER, $PERMISSIONS_ALREADY_LOGGED, $SITE_INFO;
    if ($PERMISSION_CHECK_LOGGER === NULL) {
        $file_path = get_custom_file_base() . '/data_custom/permissioncheckslog.php';
        if ((!isset($SITE_INFO['no_extra_logs']) || $SITE_INFO['no_extra_logs'] == '0') && is_file($file_path) && is_writable_wrap($file_path)) {
            $PERMISSION_CHECK_LOGGER = fopen($file_path, 'at');
            if (!function_exists('get_self_url')) {
                require_code('tempcode');
                require_code('urls');
            }
            $self_url = get_self_url(true);
            if (!is_string($self_url)) {
                $self_url = get_self_url_easy();
            }
            // A weirdness can happen here. If some kind of fatal error happens then output buffers can malfunction making it impossible to use Tempcode as above. So we fall back to this. (This function may be called in a fatal error due to the 'display_php_errors' permissions).
            fwrite($PERMISSION_CHECK_LOGGER, chr(10) . chr(10) . date('Y/m/d h:m:i') . ' -- ' . $self_url . ' -- ' . $GLOBALS['FORUM_DRIVER']->get_username(get_member()) . chr(10));
        } else {
            $PERMISSION_CHECK_LOGGER = false;
        }
    }
    static $fbe = NULL;
    if ($fbe === NULL) {
        $fbe = function_exists('fb');
    }
    if ($PERMISSION_CHECK_LOGGER === false && (!$fbe || get_param_integer('keep_firephp', 0) == 0)) {
        return;
    }
    $sz = serialize(array($member, $op, $params));
    if (array_key_exists($sz, $PERMISSIONS_ALREADY_LOGGED)) {
        return;
    }
    $PERMISSIONS_ALREADY_LOGGED[$sz] = 1;
    if ($result) {
        return;
    }
    require_code('permissions2');
    _handle_permission_check_logging($member, $op, $params, $result);
}
Esempio n. 3
0
/**
 * Try and get a good .htaccess file built.
 * @param  resource		FTP connection to server
 */
function test_htaccess($conn)
{
    $clauses = array();
    $clauses[] = <<<END
# Disable inaccurate security scanning (ocPortal has it's own)
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
END;
    $php_value_ok = substr(ocp_srv('SERVER_SOFTWARE'), 0, 10) != 'LightSpeed';
    if ($php_value_ok) {
        $clauses[] = <<<END
# ocPortal needs uploads; many hosts leave these low
php_value post_max_size "16M"
php_value upload_max_filesize "16M"
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
# Turn insecure things off
php_flag allow_url_fopen off
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
php_flag register_globals off
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
php_value max_input_vars "2000"
php_value mbstring.func_overload "0"
# Suhosin can cause problems on configuration and Catalogue forms, which use a lot of fields
php_value suhosin.post.max_vars "2000"
php_value suhosin.request.max_vars "2000"
php_value suhosin.cookie.max_vars "400"
php_value suhosin.cookie.max_name_length "150"
php_value suhosin.post.max_value_length "100000000"
php_value suhosin.request.max_value_length "100000000"
php_value suhosin.post.max_totalname_length "10000"
php_value suhosin.request.max_totalname_length "10000"
php_flag suhosin.cookie.encrypt off
php_flag suhosin.sql.union off
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
# Put some limits up. ocPortal is stable enough not to cause problems- it'll only use higher limits when it really needs them
php_value memory_limit "128M"
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
php_value max_input_time "60"
END;
    }
    /*// NB: This'll only work in PHP6+   Bad idea, will miss temp directory
    $file_base=$GLOBALS['FILE_BASE'];
    $clauses[]=<<<END
    # Sandbox ocPortal to it's own directory
    php_value open_basedir "{$file_base}"
    END;
    */
    $clauses[] = <<<END
Options +FollowSymLinks
END;
    $clauses[] = <<<END
RewriteEngine on

# Redirect away from modules called directly by URL. Helpful as it allows you to "run" a module file in a debugger and still see it running.
RewriteRule ^([^=]*)webdav.php/([^=]*)pages/(modules|modules\\_custom)/([^/]*)\\.php\$ - [L]
RewriteRule ^([^=]*)pages/(modules|modules\\_custom)/([^/]*)\\.php\$ \$1index.php\\?page=\$3 [L,QSA,R]

# These have a specially reduced form (no need to make it too explicit that these are CEDI)
#  We shouldn't shorten them too much, or the actual zone or base url might conflict
RewriteRule ^([^=]*)pg/s/([^\\&\\?]*)/index\\.php\$ \$1index.php\\?page=cedi&id=\$2 [L,QSA]

# These have a specially reduce form (wide is implied)
RewriteRule ^([^=]*)pg/galleries/image/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=galleries&type=image&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/video/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=galleries&type=video&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/iotds/view/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=iotds&type=view&id=\$2&wide=1\$3 [L,QSA]

# These are standard patterns
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=\$2&type=\$3&id=\$4\$5 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=\$2&type=\$3\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=\$2\$3 [L,QSA]
# This one is weird... apache strips out // and turns to /, thus requiring an extra pattern...
RewriteRule ^([^=]*)pg/index\\.php(.*)\$ \$1index.php\\?page=\$3 [L,QSA]

# Now the same, but without any additional parameters (and thus no index.php)
RewriteRule ^([^=]*)pg/s/([^\\&\\?]*)\$ \$1index.php\\?page=cedi&id=\$2 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/image/([^\\&\\?]*)\$ \$1index.php\\?page=galleries&type=image&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/video/([^\\&\\?]*)\$ \$1index.php\\?page=galleries&type=video&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/iotds/view/([^\\&\\?]*)\$ \$1index.php\\?page=iotds&type=view&id=\$2&wide=1 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/([^\\&\\?]*)/\$ \$1index.php\\?page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/([^\\&\\?]*)\$ \$1index.php\\?page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)\$ \$1index.php\\?page=\$2&type=\$3 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)\$ \$1index.php\\?page=\$2 [L,QSA]

# And these for those nasty situations where index.php was missing and we couldn't do anything about it (usually due to keep_session creeping into a semi-cached URL)
RewriteRule ^([^=]*)pg/s/([^\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$3&page=cedi&id=\$2 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/image/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$5&page=galleries&type=image&id=\$2&wide=1&\$3 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/video/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$5&page=galleries&type=video&id=\$2&wide=1&\$3 [L,QSA]
RewriteRule ^([^=]*)pg/iotds/view/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$3&page=iotds&type=view&id=\$2&wide=1 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?\\.]*)/([^/\\&\\?\\.]*)/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$5&page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?\\.]*)/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$4&page=\$2&type=\$3 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$3&page=\$2 [L,QSA]

# These have a specially reduced form (no need to make it too explicit that these are CEDI)
#  We shouldn't shorten them too much, or the actual zone or base url might conflict
RewriteRule ^(site|forum|adminzone|cms|collaboration)/s/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=cedi&id=\$2 [L,QSA]
RewriteRule ^s/([^\\&\\?]*)\\.htm\$ index\\.php\\?page=cedi&id=\$1 [L,QSA]

# These have a specially reduce form (wide is implied)
RewriteRule ^(site|forum|adminzone|cms|collaboration)/galleries/image/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=galleries&type=image&id=\$2&wide=1 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/galleries/video/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=galleries&type=video&id=\$2&wide=1 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/iotds/view/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=iotds&type=view&id=\$2&wide=1 [L,QSA]

# These are standard patterns
RewriteRule ^(site|forum|adminzone|cms|collaboration)/([^/\\&\\?]+)/([^/\\&\\?]*)/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/([^/\\&\\?]+)/([^/\\&\\?]*)\\.htm\$ \$1/index.php\\?page=\$2&type=\$3 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/([^/\\&\\?]+)\\.htm\$ \$1/index.php\\?page=\$2 [L,QSA]
RewriteRule ^([^/\\&\\?]+)/([^/\\&\\?]*)/([^\\&\\?]*)\\.htm\$ index.php\\?page=\$1&type=\$2&id=\$3 [L,QSA]
RewriteRule ^([^/\\&\\?]+)/([^/\\&\\?]*)\\.htm\$ index.php\\?page=\$1&type=\$2 [L,QSA]
RewriteRule ^([^/\\&\\?]+)\\.htm\$ index.php\\?page=\$1 [L,QSA]
END;
    $clauses[] = <<<END
order allow,deny
# IP bans go here (leave this comment here! If this file is writeable, ocPortal will write in IP bans below, in sync with it's own DB-based banning - this makes DOS/hack attack prevention stronger)
# deny from xxx.xx.x.x (leave this comment here!)
allow from all
END;
    $base = dirname(ocp_srv('PHP_SELF'));
    $clauses[] = <<<END
<FilesMatch !"\\.(jpg|jpeg|gif|png|ico)\$">
ErrorDocument 404 {$base}/index.php?page=404
</FilesMatch>
END;
    if (is_writable_wrap(get_file_base() . '/exports/mods') && (!file_exists(get_file_base() . '/.htaccess') || trim(file_get_contents(get_file_base() . '/.htaccess')) == '')) {
        global $HTTP_MESSAGE;
        $domain = ocp_srv('HTTP_HOST');
        if (substr($domain, 0, 4) == 'www.') {
            $domain = substr($domain, 4);
        }
        $colon_pos = strpos($domain, ':');
        if ($colon_pos !== false) {
            $domain = substr($domain, 0, $colon_pos);
        }
        $pos = strpos(ocp_srv('PHP_SELF'), 'install.php');
        if ($pos === false) {
            $pos = strlen(ocp_srv('PHP_SELF'));
        } else {
            $pos--;
        }
        $port = ocp_srv('SERVER_PORT');
        if ($port == '' || $port == '80' || $port == '443') {
            $port = '';
        } else {
            $port = ':' . $port;
        }
        $base_url = post_param('base_url', 'http://' . $domain . $port . substr(ocp_srv('PHP_SELF'), 0, $pos));
        if (substr($base_url, -1) == '/') {
            $base_url = substr($base_url, 0, strlen($base_url) - 1);
        }
        foreach ($clauses as $i => $clause) {
            $myfile = fopen(get_file_base() . '/exports/mods/index.php', 'wt');
            fwrite($myfile, "<" . "?php\n\t\t\t@header('Expires: Mon, 20 Dec 1998 01:00:00 GMT');\n\t\t\t@header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');\n\t\t\t@header('Pragma: no-cache'); // for proxies, and also IE\n\t\t\t");
            fclose($myfile);
            $myfile = fopen(get_file_base() . '/exports/mods/.htaccess', 'wt');
            fwrite($myfile, $clause);
            fclose($myfile);
            $HTTP_MESSAGE = '';
            http_download_file($base_url . '/exports/mods/index.php', NULL, false);
            if ($HTTP_MESSAGE != '200') {
                $clauses[$i] = NULL;
            }
            unlink(get_file_base() . '/exports/mods/.htaccess');
        }
        $out = '';
        foreach ($clauses as $i => $clause) {
            if (!is_null($clause)) {
                $out .= $clause . chr(10) . chr(10);
            }
        }
        if (is_suexec_like()) {
            @unlink(get_file_base() . '/.htaccess');
            $tmp = fopen(get_file_base() . '/.htaccess', 'wb');
            fwrite($tmp, $out);
            fclose($tmp);
        } else {
            @ftp_delete($conn, '.htaccess');
            $tmp = fopen(get_file_base() . '/ocp_inst_tmp/tmp', 'wb');
            fwrite($tmp, $out);
            fclose($tmp);
            @ftp_put($conn, '.htaccess', get_file_base() . '/ocp_inst_tmp/tmp', FTP_TEXT);
            @ftp_site($conn, 'CHMOD 644 .htaccess');
        }
    }
}
Esempio n. 4
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;
}
Esempio n. 5
0
/**
 * Find whether we can get away with natural file access, not messing with AFMs, world-writability, etc.
 *
 * @return boolean		Whether we have this
 */
function is_suexec_like()
{
    return function_exists('posix_getuid') && strpos(@ini_get('disable_functions'), 'posix_getuid') === false && !isset($_SERVER['HTTP_X_MOSSO_DT']) && is_integer(@posix_getuid()) && @posix_getuid() == @fileowner(get_file_base() . '/' . (running_script('install') ? 'install.php' : 'index.php')) || is_writable_wrap(get_file_base() . '/' . (running_script('index') ? 'index.php' : 'install.php'));
}
Esempio n. 6
0
 /**
  * Handle IPN's. The function may produce output, which would be returned to the Payment Gateway. The function may do transaction verification.
  *
  * @return array	A long tuple of collected data.
  */
 function handle_transaction()
 {
     if (file_exists(get_file_base() . '/data_custom/ecommerce.log') && is_writable_wrap(get_file_base() . '/data_custom/ecommerce.log')) {
         $myfile = fopen(get_file_base() . '/data_custom/ecommerce.log', 'at');
         fwrite($myfile, serialize($_POST) . chr(10));
         fclose($myfile);
     }
     // assign posted variables to local variables
     $purchase_id = post_param_integer('custom', '-1');
     $txn_type = post_param('txn_type', NULL);
     if ($txn_type == 'cart') {
         require_lang('shopping');
         $item_name = do_lang('CART_ORDER', $purchase_id);
     } else {
         $item_name = substr(post_param('txn_type', ''), 0, 6) == 'subscr' ? '' : post_param('item_name', '');
     }
     $payment_status = post_param('payment_status', '');
     // May be blank for subscription
     $reason_code = post_param('reason_code', '');
     $pending_reason = post_param('pending_reason', '');
     $memo = post_param('memo', '');
     $mc_gross = post_param('mc_gross', '');
     // May be blank for subscription
     $tax = post_param('tax', '');
     if ($tax != '' && intval($tax) > 0 && $mc_gross != '') {
         $mc_gross = float_to_raw_string(floatval($mc_gross) - floatval($tax));
     }
     $mc_currency = post_param('mc_currency', '');
     // May be blank for subscription
     $txn_id = post_param('txn_id', '');
     // May be blank for subscription
     $parent_txn_id = post_param('parent_txn_id', '-1');
     $receiver_email = post_param('receiver_email');
     // post back to PayPal system to validate
     if (!ecommerce_test_mode()) {
         require_code('files');
         $pure_post = isset($GLOBALS['PURE_POST']) ? $GLOBALS['PURE_POST'] : $_POST;
         $x = 0;
         $res = mixed();
         do {
             $res = http_download_file('http://' . (ecommerce_test_mode() ? 'www.sandbox.paypal.com' : 'www.paypal.com') . '/cgi-bin/webscr', NULL, false, false, 'ocPortal', $pure_post + array('cmd' => '_notify-validate'));
             $x++;
         } while (is_null($res) && $x < 3);
         if (is_null($res)) {
             my_exit(do_lang('IPN_SOCKET_ERROR'));
         }
         if (!(strcmp($res, 'VERIFIED') == 0)) {
             if (post_param('txn_type', '') == 'send_money') {
                 exit('Unexpected');
             }
             // PayPal has been seen to mess up on send_money transactions, making the IPN unverifiable
             my_exit(do_lang('IPN_UNVERIFIED') . ' - ' . $res . ' - ' . flatten_slashed_array($pure_post), strpos($res, '<html') !== false);
         }
     }
     $txn_type = str_replace('-', '_', post_param('txn_type'));
     if ($txn_type == 'subscr-modify') {
         $payment_status = 'SModified';
         $txn_id = post_param('subscr_id') . '-m';
     } elseif ($txn_type == 'subscr_signup') {
         $payment_status = 'Completed';
         $mc_gross = post_param('mc_amount3');
         if (post_param_integer('recurring') != 1) {
             my_exit(do_lang('IPN_SUB_RECURRING_WRONG'));
         }
         $txn_id = post_param('subscr_id');
     } elseif ($txn_type == 'subscr_eot' || $txn_type == 'recurring_payment_suspended_due_to_max_failed_payment') {
         $payment_status = 'SCancelled';
         $txn_id = post_param('subscr_id') . '-c';
     } elseif ($txn_type == 'subscr_payment' || $txn_type == 'subscr_failed' || $txn_type == 'subscr_cancel') {
         exit;
     }
     $primary_paypal_email = get_value('primary_paypal_email');
     if (!is_null($primary_paypal_email)) {
         if ($receiver_email != $primary_paypal_email) {
             my_exit(do_lang('IPN_EMAIL_ERROR'));
         }
     } else {
         if ($receiver_email != $this->_get_payment_address()) {
             my_exit(do_lang('IPN_EMAIL_ERROR'));
         }
     }
     if (addon_installed('shopping')) {
         $this->store_shipping_address($purchase_id);
     }
     return array($purchase_id, $item_name, $payment_status, $reason_code, $pending_reason, $memo, $mc_gross, $mc_currency, $txn_id, $parent_txn_id);
 }
Esempio n. 7
0
 /**
  * Standard modular file writing function for OcCLE FS hooks.
  *
  * @param  array	The current meta-directory path
  * @param  string	The root node of the current meta-directory
  * @param  string	The file name
  * @param  string	The new file contents
  * @param  array	A reference to the OcCLE filesystem object
  * @return boolean	Success?
  */
 function write_file($meta_dir, $meta_root_node, $file_name, $contents, &$occle_fs)
 {
     $file_name = filter_naughty($file_name);
     $path = get_custom_file_base() . '/data/modules/admin_occle';
     foreach ($meta_dir as $meta_dir_section) {
         $path .= '/' . filter_naughty($meta_dir_section);
     }
     if (is_dir($path) && (file_exists($path . '/' . $file_name) && is_writable_wrap($path . '/' . $file_name) || !file_exists($path . '/' . $file_name) && is_writable_wrap($path))) {
         $fh = @fopen($path . '/' . $file_name, 'wt') or intelligent_write_error($path . '/' . $file_name);
         $output = fwrite($fh, $contents);
         fclose($fh);
         if ($output < strlen($contents)) {
             warn_exit(do_lang_tempcode('COULD_NOT_SAVE_FILE'));
         }
         fix_permissions($path . '/' . $file_name);
         sync_file($path . '/' . $file_name);
         return $output;
     } else {
         return false;
     }
     //File doesn't exist
 }
Esempio n. 8
0
/**
 * This is it - the start of rendering of a website page.
 * Take in all inputs, sends them to the correct functions to process, gathers up all the outputs, sticks them together and echoes them.
 */
function do_site()
{
    // More SEO redirection (monikers)
    // Does this URL arrangement support monikers?
    $url_id = get_param('id', NULL, true);
    if ($url_id !== NULL && url_monikers_enabled()) {
        $type = get_param('type', 'misc');
        $looking_for = '_SEARCH:' . get_page_name() . ':' . $type . ':_WILD';
        $hooks = find_all_hooks('systems', 'content_meta_aware');
        $ob_info = NULL;
        foreach (array_keys($hooks) as $hook) {
            require_code('hooks/systems/content_meta_aware/' . filter_naughty($hook));
            $ob = object_factory('Hook_content_meta_aware_' . $hook, true);
            if ($ob === NULL) {
                continue;
            }
            $ob_info = $ob->info();
            $ob_info['view_pagelink_pattern'] = preg_replace('#:[^:]*$#', ':_WILD', $ob_info['view_pagelink_pattern']);
            if ($ob_info['view_pagelink_pattern'] == $looking_for && $ob_info['support_url_monikers']) {
                if (is_numeric($url_id)) {
                    $correct_moniker = find_id_moniker(array('page' => get_page_name(), 'type' => get_param('type', 'misc'), 'id' => $url_id));
                    if ($correct_moniker !== NULL && $correct_moniker != $url_id && count($_POST) == 0) {
                        header('HTTP/1.0 301 Moved Permanently');
                        $_new_url = build_url(array('page' => '_SELF', 'id' => $correct_moniker), '_SELF', NULL, true);
                        $new_url = $_new_url->evaluate();
                        header('Location: ' . $new_url);
                        exit;
                    }
                } else {
                    // See if it is deprecated
                    if (strpos(get_db_type(), 'mysql') !== false) {
                        $monikers = $GLOBALS['SITE_DB']->query_select('url_id_monikers USE INDEX (uim_moniker)', array('m_resource_id', 'm_deprecated'), array('m_resource_page' => get_page_name(), 'm_resource_type' => get_param('type', 'misc'), 'm_moniker' => $url_id));
                    } else {
                        $monikers = $GLOBALS['SITE_DB']->query_select('url_id_monikers', array('m_resource_id', 'm_deprecated'), array('m_resource_page' => get_page_name(), 'm_resource_type' => get_param('type', 'misc'), 'm_moniker' => $url_id));
                    }
                    if (!array_key_exists(0, $monikers)) {
                        warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
                    }
                    $deprecated = $monikers[0]['m_deprecated'] == 1;
                    if ($deprecated && count($_POST) == 0) {
                        $correct_moniker = find_id_moniker(array('page' => get_page_name(), 'type' => get_param('type', 'misc'), 'id' => $monikers[0]['m_resource_id']));
                        header('HTTP/1.0 301 Moved Permanently');
                        $_new_url = build_url(array('page' => '_SELF', 'id' => $correct_moniker), '_SELF', NULL, true);
                        $new_url = $_new_url->evaluate();
                        header('Location: ' . $new_url);
                        exit;
                    } else {
                        $_GET['id'] = $monikers[0]['m_resource_id'];
                        // We need to know the ID number rather than the moniker
                    }
                }
                break;
            }
        }
    }
    // Any messages to output?
    if (get_param_integer('redirected', 0) == 1) {
        $messages = $GLOBALS['SITE_DB']->query_select('messages_to_render', array('r_message', 'r_type'), array('r_session_id' => get_session_id()), 'ORDER BY r_time DESC');
        foreach ($messages as $message) {
            if ($GLOBALS['XSS_DETECT']) {
                ocp_mark_as_escaped($message['r_message']);
            }
            attach_message(protect_from_escaping($message['r_message']), $message['r_type']);
        }
        if (count($messages) != 0) {
            $GLOBALS['SITE_DB']->query('DELETE FROM ' . $GLOBALS['SITE_DB']->get_table_prefix() . 'messages_to_render WHERE r_session_id=' . strval((int) get_session_id()) . ' OR r_time<' . strval(time() - 60 * 60));
        }
    }
    if (in_safe_mode()) {
        $disable_safe_mode_url = get_self_url(true, true, array('keep_safe_mode' => NULL));
        attach_message(do_lang_tempcode('CURRENTLY_HAS_KEEP_SAFE_MODE', escape_html($disable_safe_mode_url)), 'notice');
    }
    if (get_param_integer('keep_fatalistic', 0) == 1) {
        $disable_fatalistic_url = get_self_url(true, true, array('keep_fatalistic' => NULL));
        attach_message(do_lang_tempcode('CURRENTLY_HAS_KEEP_FATALISTIC', escape_html($disable_fatalistic_url)), 'notice');
    }
    $special_page_type = get_param('special_page_type', 'view');
    global $ZONE;
    $keep_markers = get_param_integer('keep_markers', 0);
    $show_edit_links = get_param_integer('show_edit_links', 0);
    global $KEEP_MARKERS, $SHOW_EDIT_LINKS;
    $KEEP_MARKERS = $keep_markers == 1 || $special_page_type == 'show_markers';
    if ($KEEP_MARKERS && !headers_sent()) {
        header('Content-type: text/html; charset=' . get_charset());
    }
    $SHOW_EDIT_LINKS = $show_edit_links == 1 || $special_page_type == 'show_edit_links';
    $out_evaluated = NULL;
    if ($special_page_type != 'view' && $special_page_type != 'show_markers') {
        require_code('view_modes');
        initialise_special_page_types($special_page_type);
    }
    // Set up Xdebug profiling
    if ($special_page_type == 'profile') {
        if (function_exists('xdebug_start_profiling')) {
            xdebug_start_profiling();
        }
        // xdebug 1 style
        if (ini_get('xdebug.profiler_enable') != '1') {
            attach_message(escape_html('Profiling must be enabled in php.ini'), 'warn');
        }
        // xdebug 2 style
        if (!is_writable_wrap(ini_get('xdebug.profiler_output_dir'))) {
            attach_message(escape_html('xdebug.profiler_output_dir needs setting to a writable directory'), 'warn');
        }
    }
    // Allow the site to be closed
    $site_closed = get_option('site_closed');
    if ($site_closed == '1' && !has_specific_permission(get_member(), 'access_closed_site') && !$GLOBALS['IS_ACTUALLY_ADMIN']) {
        require_code('site2');
        closed_site();
    }
    // Work out which page we're viewing
    global $PAGE;
    $PAGE = get_page_name();
    $doing_special_page_type = $special_page_type != 'view' && $special_page_type != 'show_markers' && $special_page_type != 'show_edit_links' && $special_page_type != 'memory' && (has_specific_permission(get_member(), 'view_profiling_modes') || $GLOBALS['IS_ACTUALLY_ADMIN']);
    // Load up our frames into strings. Note that the header and the footer are fixed already.
    $middle = request_page($PAGE, true);
    global $CYCLES;
    $CYCLES = array();
    // Here we reset some Tempcode environmental stuff, because template compilation or preprocessing may have dirtied things
    if ($middle === NULL || $middle->is_definitely_empty()) {
        $GLOBALS['HTTP_STATUS_CODE'] = '404';
        if (!headers_sent()) {
            if (!browser_matches('ie') && strpos(ocp_srv('SERVER_SOFTWARE'), 'IIS') === false) {
                header('HTTP/1.0 404 Not Found');
            }
        }
        $title = get_page_title('ERROR_OCCURRED');
        $text = do_lang_tempcode('NO_PAGE_OUTPUT');
        $middle = warn_screen($title, $text, false);
    }
    // Extra stuff we can tag on (like messages)
    $additional = new ocp_tempcode();
    $site_closed = get_option('site_closed');
    // May have been JUST changed in page load - think Setup Wizard
    if ($site_closed == '1' && $PAGE != 'login' && $PAGE != 'join' && get_param_integer('wide_high', 0) == 0) {
        $additional->attach(do_template('ADDITIONAL', array('_GUID' => '03a41a91606b3ad05330e7d6f3e741c1', 'TYPE' => 'notice', 'MESSAGE' => do_lang_tempcode(has_specific_permission(get_member(), 'access_closed_site') ? 'SITE_SPECIAL_ACCESS' : 'SITE_SPECIAL_ACCESS_SU'))));
    }
    if ($GLOBALS['IS_ACTUALLY_ADMIN']) {
        $unsu_link = get_self_url(true, true, array('keep_su' => NULL));
        $su_username = $GLOBALS['FORUM_DRIVER']->get_username(get_member());
        $additional->attach(do_template('ADDITIONAL', array('_GUID' => '13a41a91606b3ad05330e7d6f3e741c1', 'TYPE' => 'notice', 'MESSAGE' => do_lang_tempcode('USING_SU', escape_html($unsu_link), escape_html($su_username)))));
    }
    $out = new ocp_tempcode();
    // This is important - it makes sure the tempcode tree appears nicely
    $middle->handle_symbol_preprocessing();
    // Due to the '->evaluate()' below, plus so that some symbol preprocessing can be passed into header
    $out->attach(do_header());
    if (function_exists('memory_get_usage') && get_param('special_page_type', '') == 'memory') {
        if (function_exists('memory_get_peak_usage')) {
            $memory_usage = memory_get_peak_usage();
        } else {
            $memory_usage = memory_get_usage();
        }
        $additional->attach(do_template('ADDITIONAL', array('_GUID' => 'd605c0d111742a8cd2d4ef270a1e5fe1', 'TYPE' => 'inform', 'MESSAGE' => do_lang_tempcode('MEMORY_USAGE', float_format(round(floatval($memory_usage) / 1024.0 / 1024.0, 2))))));
    }
    // Whack it into our global template
    global $ATTACHED_MESSAGES;
    $global_template = 'GLOBAL';
    if (get_option('show_docs') == '0') {
        $GLOBALS['HELPER_PANEL_TUTORIAL'] = '';
    }
    $helper_panel_pic = $GLOBALS['HELPER_PANEL_PIC'];
    if ($helper_panel_pic != '') {
        if (find_theme_image($helper_panel_pic, true) == '') {
            $helper_panel_pic = '';
        }
    }
    $global = do_template($global_template, array('HELPER_PANEL_TUTORIAL' => $GLOBALS['HELPER_PANEL_TUTORIAL'], 'HELPER_PANEL_HTML' => $GLOBALS['HELPER_PANEL_HTML'], 'HELPER_PANEL_TEXT' => $GLOBALS['HELPER_PANEL_TEXT'], 'HELPER_PANEL_PIC' => $helper_panel_pic, 'MIDDLE' => $doing_special_page_type ? $middle : $middle->evaluate(), 'MESSAGE_TOP' => $ATTACHED_MESSAGES, 'MESSAGE' => $additional, 'BREADCRUMBS' => breadcrumbs()));
    unset($middle);
    $out->attach($global);
    $out->attach(do_footer());
    $out->handle_symbol_preprocessing();
    if (get_value('xhtml_strict') === '1') {
        $out = make_xhtml_strict($out);
    }
    // Validation
    $novalidate = get_param_integer('keep_novalidate', get_param_integer('novalidate', 0));
    $show_edit_links = get_param_integer('show_edit_links', 0);
    if ((in_array(ocp_srv('HTTP_HOST'), array('localhost', 'test.ocportal.com')) || $GLOBALS['FORUM_DRIVER']->is_staff(get_member())) && ($special_page_type == 'code' || $novalidate == 0 && get_option('validation') == '1') && $GLOBALS['REFRESH_URL'][0] == '' && $show_edit_links == 0) {
        require_code('view_modes');
        $out_evaluated = $out->evaluate(NULL, false);
        do_xhtml_validation($out_evaluated, $special_page_type == 'code' && get_param_integer('preview_mode', NULL) === NULL, get_param_integer('preview_mode', 0));
    }
    // Cacheing for spiders
    if (running_script('index') && count($_POST) == 0 && isset($GLOBALS['SITE_INFO']['fast_spider_cache']) && $GLOBALS['SITE_INFO']['fast_spider_cache'] == '1' && is_guest()) {
        $bot_type = get_bot_type();
        if (($bot_type !== NULL || isset($GLOBALS['SITE_INFO']['any_guest_cached_too']) && $GLOBALS['SITE_INFO']['any_guest_cached_too'] == '1') && can_fast_spider_cache()) {
            $fast_cache_path = get_custom_file_base() . '/persistant_cache/' . md5(serialize(get_self_url_easy()));
            if ($bot_type === NULL) {
                $fast_cache_path .= '__non-bot';
            }
            if (!array_key_exists('js_on', $_COOKIE)) {
                $fast_cache_path .= '__no-js';
            }
            if (is_mobile()) {
                $fast_cache_path .= '_mobile';
            }
            $fast_cache_path .= '.gcd';
            if (!is_dir(get_custom_file_base() . '/persistant_cache/')) {
                if (@mkdir(get_custom_file_base() . '/persistant_cache/', 0777)) {
                    fix_permissions(get_custom_file_base() . '/persistant_cache/', 0777);
                    sync_file(get_custom_file_base() . '/persistant_cache/');
                } else {
                    intelligent_write_error($fast_cache_path);
                }
            }
            $out_evaluated = $out->evaluate(NULL, false);
            $myfile = @fopen($fast_cache_path, 'wb') or intelligent_write_error($fast_cache_path);
            if (function_exists('gzencode')) {
                fwrite($myfile, gzencode($out_evaluated, 9));
            } else {
                fwrite($myfile, $out_evaluated);
            }
            fclose($myfile);
            fix_permissions($fast_cache_path);
            sync_file($fast_cache_path);
        }
    }
    if ($doing_special_page_type) {
        special_page_types($special_page_type, $out, $out_evaluated);
    }
    // We calculated the time before outputting so that latency and bandwidth do not adversely affect the result
    global $PAGE_START_TIME, $PAGE_STRING;
    $page_generation_time = microtime_diff($PAGE_START_TIME, microtime(false));
    if (!$GLOBALS['QUICK_REDIRECT']) {
        if ($out_evaluated !== NULL) {
            echo $out_evaluated;
        } else {
            $GLOBALS['FINISHING_OUTPUT'] = true;
            $out->evaluate_echo();
        }
    }
    // Finally, stats
    if ($PAGE_STRING !== NULL) {
        log_stats($PAGE_STRING, intval($page_generation_time));
    }
    // When someone hits the Admin Zone front page.
    if ($ZONE['zone_name'] == 'adminzone' && get_page_name() == 'start') {
        // Security feature admins can turn on
        require_code('notifications');
        $current_username = $GLOBALS['FORUM_DRIVER']->get_username(get_member());
        $subject = do_lang('AFA_NOTIFICATION_MAIL_SUBJECT', $current_username, get_site_name(), get_ip_address());
        $mail = do_lang('AFA_NOTIFICATION_MAIL', comcode_escape(get_site_name()), comcode_escape($current_username), comcode_escape(get_ip_address()));
        dispatch_notification('adminzone_frontpage_accessed', NULL, $subject, $mail);
        // Track very basic details of what sites use ocPortal. You can remove if you like.
        if (preg_match('#^localhost[\\.\\:$]?#', ocp_srv('HTTP_HOST')) == 0) {
            global $EXPIRE, $KEY;
            $timeout_before = @ini_get('default_socket_timeout');
            @ini_set('default_socket_timeout', '3');
            http_download_file('http://ocportal.com/user.php?url=' . urlencode(get_base_url()) . '&name=' . urlencode(get_site_name()) . '&registered=2&key=' . ($KEY === NULL ? '' : strval($KEY)) . '&expire=' . ($EXPIRE === NULL ? '' : strval($EXPIRE)) . '&version=' . urlencode(ocp_version_full()), NULL, false);
            @ini_set('default_socket_timeout', $timeout_before);
        }
    }
    // Little disk space check
    $last_space_check = get_value('last_space_check');
    if ($last_space_check === NULL || intval($last_space_check) < time() - 60 * 60 * 3) {
        set_value('last_space_check', strval(time()));
        $low_space_check = intval(get_option('low_space_check')) * 1024 * 1024;
        $disk_space = @disk_free_space(get_file_base());
        if (is_integer($disk_space) && $disk_space < $low_space_check) {
            require_code('notifications');
            $subject = do_lang('LOW_DISK_SPACE_SUBJECT', NULL, NULL, NULL, get_site_default_lang());
            $message = do_lang('LOW_DISK_SPACE_MAIL', strval(intval(round($disk_space / 1024 / 1024))), NULL, NULL, get_site_default_lang());
            dispatch_notification('low_disk_space', NULL, $subject, $message, NULL, A_FROM_SYSTEM_PRIVILEGED);
        }
    }
    //exit();
}
/**
 * Get the fields that need to be filled in to know how to do an AFM connection.
 *
 * @return tempcode	The form fields.
 */
function get_afm_form_fields()
{
    require_code('form_templates');
    $fields = new ocp_tempcode();
    $ftp_username = get_value('ftp_username');
    $ftp_directory = get_value('ftp_directory');
    $ftp_domain = get_value('ftp_domain');
    $_uses_ftp = running_script('upgrader') ? '0' : get_value('uses_ftp');
    if (is_null($_uses_ftp)) {
        $uses_ftp = !is_writable_wrap(get_file_base() . '/adminzone/index.php');
    } else {
        $uses_ftp = $_uses_ftp == '1';
    }
    // Domain
    if (is_null($ftp_domain)) {
        if (array_key_exists('ftp_domain', $GLOBALS['SITE_INFO'])) {
            $ftp_domain = $GLOBALS['SITE_INFO']['ftp_domain'];
        } else {
            $domain = ocp_srv('HTTP_HOST');
            if (substr($domain, 0, 4) == 'www.') {
                $domain = substr($domain, 4);
            }
            $colon_pos = strpos($domain, ':');
            if ($colon_pos !== false) {
                $ftp_domain = substr($domain, 0, $colon_pos);
            } else {
                $ftp_domain = $domain;
            }
        }
    }
    // Username
    if (is_null($ftp_username)) {
        if (array_key_exists('ftp_username', $GLOBALS['SITE_INFO'])) {
            $ftp_username = $GLOBALS['SITE_INFO']['ftp_username'];
        } else {
            if (function_exists('posix_getpwuid') && strpos(@ini_get('disable_functions'), 'posix_getpwuid') === false) {
                $u_info = posix_getpwuid(fileowner(get_file_base() . '/index.php'));
                if ($u_info !== false) {
                    $ftp_username = $u_info['name'];
                } else {
                    $ftp_username = '';
                }
            } else {
                $ftp_username = '';
            }
            if (is_null($ftp_username)) {
                $ftp_username = '';
            }
        }
    }
    // Directory
    if (is_null($ftp_directory)) {
        if (array_key_exists('ftp_directory', $GLOBALS['SITE_INFO'])) {
            $ftp_directory = $GLOBALS['SITE_INFO']['ftp_directory'];
        } else {
            $pos = strpos($_SERVER['PHP_SELF'], 'adminzone/index.php');
            if ($pos === false && get_zone_name() != '') {
                $pos = strpos($_SERVER['PHP_SELF'], get_zone_name() . '/index.php');
            }
            if ($pos === false) {
                $pos = strpos($_SERVER['PHP_SELF'], 'data/');
            }
            if ($pos === false) {
                $pos = strpos($_SERVER['PHP_SELF'], 'data_custom/');
            }
            if ($pos === false) {
                $pos = strpos($_SERVER['PHP_SELF'], 'cms/index.php');
            }
            if ($pos === false) {
                $pos = strpos($_SERVER['PHP_SELF'], 'site/index.php');
            }
            $dr = array_key_exists('DOCUMENT_ROOT', $_SERVER) ? $_SERVER['DOCUMENT_ROOT'] : (array_key_exists('DOCUMENT_ROOT', $_ENV) ? $_ENV['DOCUMENT_ROOT'] : '');
            if (strpos($dr, '/') !== false) {
                $dr_parts = explode('/', $dr);
            } else {
                $dr_parts = explode('\\', $dr);
            }
            $webdir_stub = $dr_parts[count($dr_parts) - 1];
            $ftp_directory = '/' . $webdir_stub . substr($_SERVER['PHP_SELF'], 0, $pos);
        }
    }
    $fields->attach(do_template('FORM_SCREEN_FIELD_SPACER', array('TITLE' => do_lang_tempcode('SETTINGS'))));
    if (ini_get('safe_mode') != '1') {
        $fields->attach(form_input_tick(do_lang_tempcode('NEED_FTP'), do_lang_tempcode('DESCRIPTION_NEED_FTP'), 'uses_ftp', $uses_ftp));
    }
    $fields->attach(form_input_line(do_lang_tempcode('FTP_DOMAIN'), '', 'ftp_domain', $ftp_domain, false));
    $fields->attach(form_input_line(do_lang_tempcode('FTP_DIRECTORY'), do_lang_tempcode('FTP_FOLDER'), 'ftp_directory', $ftp_directory, false));
    $fields->attach(form_input_line(do_lang_tempcode('FTP_USERNAME'), '', 'ftp_username', $ftp_username, false));
    $fields->attach(form_input_password(do_lang_tempcode('FTP_PASSWORD'), '', 'ftp_password', false));
    $fields->attach(do_template('FORM_SCREEN_FIELD_SPACER', array('TITLE' => do_lang_tempcode('ACTIONS'))));
    $fields->attach(form_input_tick(do_lang_tempcode('REMEMBER_PASSWORD'), do_lang_tempcode('DESCRIPTION_REMEMBER_PASSWORD'), 'remember_password', false));
    return $fields;
}
Esempio n. 10
0
/**
 * Standard code module initialisation function.
 */
function init__global2()
{
    global $BOOTSTRAPPING, $CHECKING_SAFEMODE, $BAD_WORD_CHARS, $FIXED_WORD_CHARS, $FIXED_WORD_CHARS_HTML, $BROWSER_DECACHEING, $CHARSET, $TEMP_CHARSET, $RELATIVE_PATH, $CURRENTLY_HTTPS, $RUNNING_SCRIPT_CACHE, $SERVER_TIMEZONE, $HAS_SET_ERROR_HANDLER, $DYING_BADLY, $XSS_DETECT, $SITE_INFO, $JAVASCRIPTS, $JAVASCRIPT, $CSSS, $IN_MINIKERNEL_VERSION, $EXITING, $FILE_BASE, $MOBILE, $CACHE_TEMPLATES, $BASE_URL_HTTP, $BASE_URL_HTTPS, $WORDS_TO_FILTER, $FIELD_RESTRICTIONS, $VALID_ENCODING, $CONVERTED_ENCODING, $MICRO_BOOTUP, $MICRO_AJAX_BOOTUP, $QUERY_LOG, $_CREATED_FILES, $CURRENT_SHARE_USER, $CACHE_FIND_SCRIPT;
    if (str_replace(array('on', 'true', 'yes'), array('1', '1', '1'), strtolower(ini_get('output_buffering'))) == '1') {
        @ob_end_clean();
    }
    if (array_key_exists('HTTP_X_REWRITE_URL', $_SERVER)) {
        foreach ($_GET as $key => $val) {
            if ($key[0] == '?') {
                unset($_GET[$key]);
                $_GET[substr($key, 1)] = $val;
            }
        }
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
    } elseif (!array_key_exists('REQUEST_URI', $_SERVER) && !array_key_exists('REQUEST_URI', $_ENV)) {
        $_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'];
        $first = true;
        foreach ($_GET as $key => $val) {
            $_SERVER['REQUEST_URI'] .= $first ? '?' : '&';
            $_SERVER['REQUEST_URI'] .= urlencode($key) . '=' . urlencode($val);
            $first = false;
        }
    }
    if (array_key_exists('SCRIPT_FILENAME', $_SERVER) && !array_key_exists('PHP_SELF', $_SERVER)) {
        $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_FILENAME'];
    } elseif (array_key_exists('SCRIPT_NAME', $_SERVER) && defined('HIPHOP_PHP')) {
        $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
    }
    @header('Expires: Mon, 20 Dec 1998 01:00:00 GMT');
    @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    @header('Cache-Control: no-cache, max-age=0');
    @header('Pragma: no-cache');
    // for proxies, and also IE
    if (is_file('closed.html') && get_param_integer('keep_force_open', 0) == 0) {
        if (strpos($_SERVER['PHP_SELF'], 'upgrader.php') === false && strpos($_SERVER['PHP_SELF'], 'execute_temp.php') === false && (!isset($SITE_INFO['no_extra_closed_file']) || $SITE_INFO['no_extra_closed_file'] == '0')) {
            if (@strpos($_SERVER['SERVER_SOFTWARE'], 'IIS') === false) {
                header('HTTP/1.0 503 Service Temporarily Unavailable');
            }
            header('Location: ' . (is_file($RELATIVE_PATH . 'closed.html') ? 'closed.html' : '../closed.html'));
            exit;
        }
    }
    // Cover up holes in old PHP versions functionality
    if (!function_exists('str_word_count')) {
        /**
         * Isolate the words in the input string.
         *
         * @param  string			String to count words in
         * @param  integer		The format
         * @set    0 1 2
         * @return mixed			Typically a list - the words of the input string
         */
        function str_word_count($input, $format = 0)
        {
            //count words
            $pattern = "/[^(\\w|\\d|\\'|\"|\\.|\\!|\\?|;|,|\\|\\/|\\-\\-|:|\\&|@)]+/";
            $all_words = trim(preg_replace($pattern, ' ', $input));
            $a = array();
            $pos = 0;
            while (true) {
                $old_pos = $pos;
                $pos = strpos($all_words, ' ', $pos);
                if ($pos === false) {
                    $a[$old_pos] = substr($all_words, $old_pos);
                    break;
                }
                $a[$old_pos] = substr($all_words, $old_pos, $pos - $old_pos);
            }
            if ($format == 0) {
                return count($a);
            }
            return $a;
        }
    }
    if (!function_exists('html_entity_decode')) {
        /**
         * Decode the HTML entitity encoded input string.
         *
         * @param  string			The text to decode
         * @param  integer		The quote style code
         * @param  ?string		Character set to decode to (NULL: default)
         * @return string			The decoded text
         */
        function html_entity_decode($input, $quote_style, $charset = NULL)
        {
            unset($quote_style);
            unset($charset);
            /*			// NB: &nbsp does not go to <space>. It's not something you use with html escaping, it's for hard-space-formatting. URL's don't contain spaces, but that's due to URL escaping (%20)
            			$replace_array=array(
            				'&amp;'=>'&',
            				'&gt;'=>'>',
            				'&lt;'=>'<',
            				'&#039;'=>'\'',
            				'&quot;'=>'"',
            			);
            
            			foreach ($replace_array as $from=>$to)
            			{
            				$input=str_replace($from,$to,$input);
            			}
            
            			return $input;*/
            $trans_tbl = get_html_translation_table(HTML_ENTITIES);
            $trans_tbl = array_flip($trans_tbl);
            return strtr($input, $trans_tbl);
        }
    }
    if (version_compare(phpversion(), '4.3.0') >= 0) {
        if (!function_exists('unichrm_hex')) {
            /**
             * Convert a unicode character number to a unicode string. Callback for preg_replace.
             *
             * @param  array					Regular expression match array.
             * @return ~string				Converted data (false: could not convert).
             */
            function unichrm_hex($matches)
            {
                return unichr(hexdec($matches[1]));
            }
        }
        if (!function_exists('unichrm')) {
            /**
             * Convert a unicode character number to a unicode string. Callback for preg_replace.
             *
             * @param  array					Regular expression match array.
             * @return ~string				Converted data (false: could not convert).
             */
            function unichrm($matches)
            {
                return unichr(intval($matches[1]));
            }
        }
        if (!function_exists('unichr')) {
            /**
             * Convert a unicode character number to a HTML-entity enabled string, using lower ASCII characters where possible.
             *
             * @param  integer				Character number.
             * @return ~string				Converted data (false: could not convert).
             */
            function unichr($c)
            {
                if ($c <= 0x7f) {
                    return chr($c);
                } else {
                    return '#&' . strval($c) . ';';
                }
            }
        }
    }
    $BOOTSTRAPPING = 1;
    $CHECKING_SAFEMODE = false;
    $BAD_WORD_CHARS = array(chr(128), chr(130), chr(131), chr(132), chr(133), chr(134), chr(135), chr(136), chr(137), chr(138), chr(139), chr(140), chr(142), chr(145), chr(146), chr(147), chr(148), chr(149), chr(150), chr(151), chr(152), chr(153), chr(154), chr(155), chr(156), chr(158), chr(159));
    $FIXED_WORD_CHARS = array('(EUR-)', ',', '{f.}', '"', '...', '-|-', '=|=', '^', '{%o}', '{~S}', '<', 'CE', '{~Z}', "'", "'", '"', '"', '-', '-', '--', '~', '(TM)', '{~s}', '>', 'ce', '{~z}', '{.Y.}');
    // some of these are Comcode shortcuts. We can't use entities as we can't assume we're converting into Comcode.
    $FIXED_WORD_CHARS_HTML = array('&#8364;', '&#8218;', '&#402;', '&#8222;', '&hellip;', '&#8224;', '&#8225;', '&#710;', '&#8240;', '&#352;', '&#8249;', '&#338;', '&#381;', "&lsquo;", "&rsquo;", '&ldquo;', '&rdquo;', '&bull;', '&ndash;', '&mdash;', '&#732;', '&trade;', '&#353;', '&#8250;', '&#339;', '&#382;', '&#376;');
    $RUNNING_SCRIPT_CACHE = array();
    $BROWSER_DECACHEING = NULL;
    $CHARSET = NULL;
    $TEMP_CHARSET = NULL;
    $CURRENTLY_HTTPS = NULL;
    $CACHE_FIND_SCRIPT = array();
    error_reporting(E_ALL);
    @ini_set('html_errors', '1');
    @ini_set('docref_root', 'http://www.php.net/manual/en/');
    @ini_set('docref_ext', '.php');
    $SERVER_TIMEZONE = function_exists('date_default_timezone_get') ? @date_default_timezone_get() : ini_get('date.timezone');
    @ini_set('date.timezone', 'UTC');
    if (function_exists('date_default_timezone_set')) {
        date_default_timezone_set('UTC');
    }
    // Needed for HPHP
    $HAS_SET_ERROR_HANDLER = false;
    $DYING_BADLY = false;
    // If ocPortal is bailing out uncontrollably, setting this will make sure the error hander does not try and suppress
    $XSS_DETECT = function_exists('ocp_mark_as_escaped');
    $GLOBALS['DEBUG_MODE'] = (!array_key_exists('debug_mode', $SITE_INFO) || $SITE_INFO['debug_mode'] == '1') && (is_dir(get_file_base() . '/.svn') || is_dir(get_file_base() . '/.git') || function_exists('ocp_mark_as_escaped')) && (!array_key_exists('keep_no_debug_mode', $_GET) || $_GET['keep_no_debug_mode'] == '0');
    $GLOBALS['SEMI_DEBUG_MODE'] = (!array_key_exists('debug_mode', $SITE_INFO) || $SITE_INFO['debug_mode'] == '1') && (is_dir(get_file_base() . '/.svn') || is_dir(get_file_base() . '/.git') || function_exists('ocp_mark_as_escaped'));
    if (function_exists('set_time_limit')) {
        @set_time_limit(60);
    }
    if ($GLOBALS['DEBUG_MODE']) {
        if (function_exists('set_time_limit')) {
            @set_time_limit(10);
        }
        @ini_set('ocproducts.type_strictness', '1');
        @ini_set('ocproducts.xss_detect', '1');
    }
    if ($GLOBALS['DEBUG_MODE']) {
        require_code('developer_tools');
    }
    $JAVASCRIPTS = array('javascript' => 1, 'javascript_thumbnails' => 1);
    if ($GLOBALS['CURRENT_SHARE_USER'] !== NULL || get_domain() == 'myocp.com') {
        $JAVASCRIPTS['javascript_ajax'] = 1;
    }
    $CSSS = array('no_cache' => 1, 'global' => 1);
    // Try and make the PHP environment as we need it
    if (function_exists('set_magic_quotes_runtime')) {
        @set_magic_quotes_runtime(0);
    }
    // @'d because it's deprecated and PHP 5.3 may give an error
    @ini_set('auto_detect_line_endings', '0');
    @ini_set('include_path', '');
    @ini_set('default_socket_timeout', '60');
    @ini_set('allow_url_fopen', '0');
    @ini_set('suhosin.executor.disable_emodifier', '1');
    // Extra security if suhosin is available
    @ini_set('suhosin.executor.multiheader', '1');
    // Extra security if suhosin is available
    @ini_set('suhosin.executor.disable_eval', '0');
    @ini_set('suhosin.executor.eval.whitelist', '');
    @ini_set('suhosin.executor.func.whitelist', '');
    // Load most basic config
    $IN_MINIKERNEL_VERSION = 0;
    $EXITING = 0;
    if (array_key_exists('use_ocf', $_GET) && running_script('upgrader')) {
        $SITE_INFO['forum_type'] = 'ocf';
        $SITE_INFO['ocf_table_prefix'] = $SITE_INFO['table_prefix'];
    }
    $CACHE_TEMPLATES = true;
    // The URL to our install (no trailing /)
    $BASE_URL_HTTP = NULL;
    $BASE_URL_HTTPS = NULL;
    $WORDS_TO_FILTER = NULL;
    $FIELD_RESTRICTIONS = NULL;
    $VALID_ENCODING = false;
    $CONVERTED_ENCODING = false;
    if (!isset($MICRO_BOOTUP)) {
        $MICRO_BOOTUP = 0;
    }
    if (!isset($MICRO_AJAX_BOOTUP)) {
        $MICRO_AJAX_BOOTUP = 0;
    }
    require_code_no_override('version');
    if ($MICRO_BOOTUP == 0 && $MICRO_AJAX_BOOTUP == 0) {
        //@header('X-Powered-By: ocPortal '.ocp_version_full().' (PHP '.phpversion().')');
        @header('X-Powered-By: ocPortal');
        // Better to keep it vague, for security reasons
        $QUERY_LOG = false;
        if (isset($_REQUEST['special_page_type']) && $_REQUEST['special_page_type'] == 'query') {
            $QUERY_LOG = true;
        }
    }
    // Most critical things
    require_code('support');
    // A lot of support code is present in this
    srand(make_seed());
    mt_srand(make_seed());
    if ($MICRO_BOOTUP == 0 && $MICRO_AJAX_BOOTUP == 0) {
        if (running_script('index') && count($_POST) == 0) {
            $bot_type = get_bot_type();
            if ($bot_type !== NULL && isset($SITE_INFO['fast_spider_cache']) && $SITE_INFO['fast_spider_cache'] != '0') {
                fast_spider_cache(true);
            }
        }
    }
    require_code('caches');
    // Recently taken out of 'support' so makes sense to load it here
    require_code('database');
    // There's nothing without the database
    if ((!isset($SITE_INFO['known_suexec']) || $SITE_INFO['known_suexec'] == '0') && !is_writable_wrap(get_file_base() . '/.htaccess')) {
        require_code('support2');
        if (ip_banned(get_ip_address())) {
            critical_error('BANNED');
        }
    }
    if (running_script('messages') && get_param('action', 'new') == 'new' && get_param_integer('routine_refresh', 0) == 0) {
        require_code('chat_poller');
        chat_poller();
    }
    if ($MICRO_BOOTUP == 0) {
        load_user_stuff();
    }
    // For any kind of niceness we need these. The order is chosen for complex dependency reasons - don't mess with it
    if ($MICRO_AJAX_BOOTUP == 0) {
        require_code('themes');
        // Output needs to know about themes
        require_code('templates');
        // So that we can do error templates
        require_code('tempcode');
        // Output is done with tempcode
        if ($MICRO_BOOTUP == 0) {
            require_code('comcode');
            // Much output goes through comcode
        }
    }
    require_code('zones');
    // Zone is needed because zones are where all ocPortal pages reside
    require_code('config');
    // Config is needed for much active stuff
    if (get_option('collapse_user_zones', true) === '1' && $RELATIVE_PATH == 'site') {
        get_base_url();
        /*force calculation first*/
        $RELATIVE_PATH = '';
    }
    require_code('users');
    // Users are important due to permissions
    if ($MICRO_BOOTUP == 0 && $MICRO_AJAX_BOOTUP == 0) {
        if (running_script('index') && count($_POST) == 0) {
            if (isset($SITE_INFO['any_guest_cached_too']) && $SITE_INFO['any_guest_cached_too'] == '1' && is_guest(NULL, true)) {
                fast_spider_cache(false);
            }
        }
    }
    $CACHE_TEMPLATES = (get_option('is_on_template_cache') == '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 ($MICRO_AJAX_BOOTUP == 0) {
        require_code('temporal');
        // Date/time functions
        require_code('files');
        // Contains fix_permissions, needed for 'lang'
        require_code('lang');
        // So that we can do language stuff (e.g. errors)
        convert_data_encodings();
        if ($MICRO_BOOTUP == 0) {
            require_code('permissions');
            // So we can check access
        }
    }
    // At this point we can display errors nicely
    $GLOBALS['SUPPRESS_ERROR_DEATH'] = false;
    set_error_handler('ocportal_error_handler');
    if (function_exists('error_get_last')) {
        register_shutdown_function('catch_fatal_errors');
    }
    $HAS_SET_ERROR_HANDLER = true;
    if ($MICRO_BOOTUP == 0) {
        if (method_exists($GLOBALS['FORUM_DRIVER'], 'forum_layer_initialise')) {
            $GLOBALS['FORUM_DRIVER']->forum_layer_initialise();
        }
    }
    if ($MICRO_AJAX_BOOTUP == 0) {
        $JAVASCRIPT = new ocp_tempcode();
    }
    if ($MICRO_BOOTUP == 0) {
        if ($IN_MINIKERNEL_VERSION != 1 && $MICRO_AJAX_BOOTUP == 0) {
            has_cookies();
            // Will determine at early point whether we have cookie support
            get_num_users_site();
            // Will kill site if there are too many users
        }
    }
    require_code('urls');
    // URL building is crucial
    @header('Content-type: text/html; charset=' . get_charset());
    if ($MICRO_AJAX_BOOTUP == 0 && $MICRO_BOOTUP == 0) {
        // Before anything gets outputted
        handle_logins();
        require_code('site');
        // This powers the site (top level page generation)
        // Are we installed?
        get_option('site_name');
    }
    // Our logging (change false to true for temporarily changing it so staff get logging)
    if (get_option('log_php_errors') == '1') {
        @ini_set('log_errors', '1');
        if (addon_installed('errorlog')) {
            @ini_set('error_log', get_custom_file_base() . '/data_custom/errorlog.php');
        }
    }
    if ($MICRO_BOOTUP == 0 && $MICRO_AJAX_BOOTUP == 0 && (get_option('display_php_errors') == '1' || running_script('upgrader') || has_specific_permission(get_member(), 'see_php_errors'))) {
        @ini_set('display_errors', '1');
    } elseif (!$GLOBALS['DEBUG_MODE']) {
        @ini_set('display_errors', '0');
    }
    // G-zip?
    @ini_set('zlib.output_compression', get_option('gzip_output') == '1' ? 'On' : 'Off');
    if (function_exists('setlocale') && $MICRO_AJAX_BOOTUP == 0) {
        $locales = explode(',', do_lang('locale'));
        setlocale(LC_ALL, $locales[0]);
        @setlocale(LC_ALL, $locales);
        unset($locales);
    }
    if ($MICRO_AJAX_BOOTUP == 0 && $MICRO_BOOTUP == 0 && (!isset($SITE_INFO['no_installer_checks']) || $SITE_INFO['no_installer_checks'] == '0')) {
        if (is_file(get_file_base() . '/install.php') && !is_file(get_file_base() . '/install_ok') && running_script('index')) {
            warn_exit(do_lang_tempcode('MUST_DELETE_INSTALLER'));
        }
    }
    if ($MICRO_AJAX_BOOTUP == 0 && $MICRO_BOOTUP == 0) {
        $changed_base_url = !array_key_exists('base_url', $SITE_INFO) && get_long_value('last_base_url') !== get_base_url(false);
        if (running_script('index') && (is_browser_decacheing() || $changed_base_url)) {
            require_code('view_modes');
            erase_tempcode_cache();
            erase_cached_templates(!$changed_base_url);
            erase_comcode_cache();
            erase_cached_language();
            persistant_cache_empty();
            if ($changed_base_url) {
                require_lang('zones');
                require_code('zones3');
                erase_comcode_page_cache();
                set_long_value('last_base_url', get_base_url(false));
            }
        }
        if (has_zone_access(get_member(), 'adminzone')) {
            $JAVASCRIPTS['javascript_staff'] = 1;
            $JAVASCRIPTS['javascript_ajax'] = 1;
            if (addon_installed('occle')) {
                $JAVASCRIPTS['javascript_button_occle'] = 1;
            }
        }
        if (addon_installed('realtime_rain') && get_option('bottom_show_realtime_rain_button', true) === '1') {
            $JAVASCRIPTS['javascript_button_realtime_rain'] = 1;
        }
    }
    /*ocp_memory_profile('startup');
    	$func=get_defined_functions();
    	print_r($func['user']);*/
    if (tacit_https() || is_page_https(get_zone_name(), get_page_name())) {
        @header('Cache-Control: private');
        @header('Pragma: private');
    }
    $BOOTSTRAPPING = 0;
    if ($GLOBALS['SEMI_DEBUG_MODE'] && $MICRO_AJAX_BOOTUP == 0) {
        if ($GLOBALS['SEMI_DEBUG_MODE']) {
            /*if ((mt_rand(0,2)==1) && ($GLOBALS['DEBUG_MODE']) && (running_script('index')))	We know this works now, so let's stop messing up our development speed
            		{
            			require_code('view_modes');
            			erase_cached_templates(true); // Stop anything trying to read a template cache item (E.g. CSS, JS) that might not exist!
            		}*/
            if (strpos(ocp_srv('HTTP_REFERER'), ocp_srv('HTTP_HOST')) !== false && strpos(ocp_srv('HTTP_REFERER'), 'keep_devtest') !== false && !running_script('attachment') && !running_script('upgrader') && strpos(ocp_srv('HTTP_REFERER'), 'login') === false && is_null(get_param('keep_devtest', NULL))) {
                $_GET['keep_devtest'] = '1';
                fatal_exit('URL not constructed properly: development mode in use but keep_devtest was not specified. This indicates that links have been made without build_url (in PHP) or keep_stub (in Javascript). Whilst not fatal this time, failure to use these functions can cause problems when your site goes live. See the ocPortal codebook for more details.');
            } else {
                $_GET['keep_devtest'] = '1';
            }
        }
        if (browser_matches('true_xhtml') && get_value('html5') !== '1' && get_value('html5') !== '_true' && get_param_integer('keep_no_xhtml', 0) == 0 && !running_script('upgrader')) {
            @header('Content-type: application/xhtml+xml; charset=' . get_charset());
        }
        if (isset($_CREATED_FILES)) {
            /**
             * Run after-tests for debug mode, to make sure coding standards are met.
             */
            function debug_mode_aftertests()
            {
                global $_CREATED_FILES, $_MODIFIED_FILES;
                // Use the info from ocProduct's custom PHP version to make sure that all files that were created/modified got synched as they should have been.
                foreach ($_CREATED_FILES as $file) {
                    if (substr($file, 0, strlen(get_file_base())) == get_file_base() && substr($file, -4) != '.log' && basename($file) != 'permissioncheckslog.php') {
                        @exit(escape_html('File not permission-synched: ' . $file));
                    }
                }
                foreach ($_MODIFIED_FILES as $file) {
                    if (strpos($file, '_cache') === false && substr($file, 0, strlen(get_file_base())) == get_file_base() && substr($file, -4) != '.log' && basename($file) != 'permissioncheckslog.php') {
                        @exit(escape_html('File not change-synched: ' . $file));
                    }
                }
                global $TITLE_CALLED, $SCREEN_TEMPLATE_CALLED, $EXITING;
                if (is_null($SCREEN_TEMPLATE_CALLED) && $EXITING == 0 && strpos(ocp_srv('PHP_SELF'), 'index.php') !== false) {
                    @exit(escape_html('No screen template called.'));
                }
                if (!$TITLE_CALLED && (is_null($SCREEN_TEMPLATE_CALLED) || $SCREEN_TEMPLATE_CALLED != '') && $EXITING == 0 && strpos(ocp_srv('PHP_SELF'), 'index.php') !== false) {
                    @exit(escape_html('No title used on screen.'));
                }
            }
            register_shutdown_function('debug_mode_aftertests');
        }
        if (ocp_srv('SCRIPT_FILENAME') != '' && $GLOBALS['DEBUG_MODE'] && strpos(ocp_srv('SCRIPT_FILENAME'), 'data_custom') === false) {
            if (@strlen(file_get_contents(ocp_srv('SCRIPT_FILENAME'), FILE_TEXT)) > 4500) {
                fatal_exit('Entry scripts (front controllers) should not be shoved full of code.');
            }
        }
    }
    // FirePHP console support, only for administrators
    if ((get_param_integer('keep_firephp', 0) == 1 || get_param_integer('keep_queries', 0) == 1) && ($GLOBALS['FORUM_DRIVER']->is_super_admin(get_member()) || $GLOBALS['IS_ACTUALLY_ADMIN'])) {
        require_code('firephp');
    }
    $default_memory_limit = get_value('memory_limit');
    if (is_null($default_memory_limit) || $default_memory_limit == '' || $default_memory_limit == '0' || $default_memory_limit == '-1') {
        $default_memory_limit = '64M';
    }
    @ini_set('memory_limit', $default_memory_limit);
    if (isset($GLOBALS['FORUM_DRIVER']) && $GLOBALS['FORUM_DRIVER']->is_super_admin(get_member())) {
        if (get_param_integer('keep_avoid_memory_limit', 0) == 1) {
            disable_php_memory_limit();
        }
        $memory_test = get_param_integer('keep_memory_limit_test', 0);
        if ($memory_test != 0 && $memory_test <= 32) {
            @ini_set('memory_limit', strval($memory_test) . 'M');
        }
    }
    if (get_option('sitewide_im', true) === '1' && running_script('index') && get_param('type', 'misc', true) != 'room') {
        require_code('chat');
        enter_chat_lobby();
    }
    // Startup hooks
    if (!running_script('upgrader')) {
        $startup_hooks = find_all_hooks('systems', 'startup');
        foreach (array_keys($startup_hooks) as $hook) {
            require_code('hooks/systems/startup/' . filter_naughty_harsh($hook));
            $ob = object_factory('Hook_startup_' . filter_naughty_harsh($hook), true);
            if ($ob === NULL) {
                continue;
            }
            $ob->run($MICRO_BOOTUP, $MICRO_AJAX_BOOTUP, 0);
        }
        if ($CURRENT_SHARE_USER !== NULL && float_to_raw_string(ocp_version_number()) != get_value('version')) {
            require_code('upgrade');
            clear_caches_2();
            version_specific();
            upgrade_modules();
            ocf_upgrade();
        }
    }
}
Esempio n. 11
0
/**
 * Remove an IP-ban.
 *
 * @param  IP				The IP address to unban
 */
function remove_ip_ban($ip)
{
    if (!addon_installed('securitylogging')) {
        return;
    }
    $GLOBALS['SITE_DB']->query_delete('usersubmitban_ip', array('ip' => $ip), '', 1);
    persistant_cache_delete('IP_BANS');
    if (is_writable_wrap(get_file_base() . '/.htaccess')) {
        $contents = file_get_contents(get_file_base() . '/.htaccess', FILE_TEXT);
        $ip_cleaned = str_replace('*', '', $ip);
        $ip_cleaned = str_replace('..', '.', $ip_cleaned);
        $ip_cleaned = str_replace('..', '.', $ip_cleaned);
        $contents = str_replace(chr(10) . 'deny from ' . $ip_cleaned . chr(10), chr(10), $contents);
        $contents = str_replace(chr(13) . 'deny from ' . $ip_cleaned . chr(13), chr(13), $contents);
        // Just in case
        $myfile = fopen(get_file_base() . '/.htaccess', 'wt');
        if (fwrite($myfile, $contents) < strlen($contents)) {
            warn_exit(do_lang_tempcode('COULD_NOT_SAVE_FILE'));
        }
        fclose($myfile);
        sync_file('.htaccess');
    }
    $GLOBALS['SITE_DB']->query_delete('hackattack', array('ip' => $ip));
}
Esempio n. 12
0
    /**
     * Standard import function.
     *
     * @param  object			The DB connection to import from
     * @param  string			The table prefix the target prefix is using
     * @param  PATH			The base directory we are importing from
     */
    function import_pages($db, $table_prefix, $file_base)
    {
        unset($db);
        unset($table_prefix);
        require_code('files2');
        $files = @get_directory_contents($file_base);
        $theme = either_param('theme');
        $convert_to_comcode = either_param_integer('convert_to_comcode', 0);
        $fix_html = either_param_integer('fix_html', 0);
        $base_url = either_param('base_url');
        if (substr($base_url, -1) == '/') {
            $base_url = substr($base_url, 0, strlen($base_url) - 1);
        }
        // Find all htm/html/php files
        $content_files = array();
        foreach ($files as $i => $file) {
            if (substr(strtolower($file), -4) == '.htm' || substr(strtolower($file), -5) == '.html' || substr(strtolower($file), -4) == '.php') {
                $content_files[] = $file;
                unset($files[$i]);
            }
        }
        if (count($content_files) == 0) {
            warn_exit(do_lang_tempcode('NO_PAGES_FOUND'));
        }
        // Discern new zones needed
        //  Note: files in directories in a deep path will be considered in a zone name changed so underscores replace slashes
        $new_zones = array();
        $current_zones = find_all_zones();
        foreach ($content_files as $file) {
            $zone = str_replace('/', '_', dirname($file));
            if ($zone == '.') {
                $zone = '';
            }
            if (!in_array($zone, $current_zones)) {
                $new_zones[] = $zone;
            }
        }
        $new_zones = array_unique($new_zones);
        // (Maybe AFM needed here - if zones have to be created, and possibly .htaccess changed to incorporate zone names in the redirects)
        if (count($new_zones) != 0) {
            require_code('abstract_file_manager');
            force_have_afm_details();
            $change_htaccess = get_option('htm_short_urls') == '1';
            $htaccess_path = get_file_base() . '/.htaccess';
            if ($change_htaccess && file_exists($htaccess_path) && is_writable_wrap($htaccess_path)) {
                $htaccess = file_get_contents($htaccess_path);
                $htaccess = preg_replace('#\\(site\\|forum\\|adminzone\\|cms\\|collaboration[^\\)]*#', '${0}|' . implode('|', $new_zones), $htaccess);
                $myfile = fopen($htaccess_path, 'wt');
                fwrite($myfile, $htaccess);
                fclose($myfile);
                fix_permissions($htaccess_path);
                sync_file($htaccess_path);
            }
            // Create new zones as needed (and set them to our chosen theme too)
            require_code('zones2');
            foreach ($new_zones as $zone) {
                actual_add_zone($zone, ucwords(str_replace('_', ' ', $zone)), 'start', '', $theme, 0, 0);
            }
        }
        // Discern cruft in htm/html via looking for best levenshtein to length ratio over a few pages; scan by tag, not by byte
        $compare_file_contents = array();
        shuffle($content_files);
        for ($i = 0; $i < min(2, count($content_files)); $i++) {
            $file_contents = file_get_contents($file_base . '/' . $content_files[$i]);
            $compare_file_contents[$content_files[$i]] = $this->_html_filter($file_contents, $fix_html, $base_url, $files, $file_base);
        }
        $cruft = array();
        if (count($compare_file_contents) > 1) {
            $to_find = array();
            if (file_exists($file_base . '/header.txt')) {
                $cruft['HEADER'] = $this->_html_filter(file_get_contents($file_base . '/header.txt'), $fix_html, $base_url, $files, $file_base);
            } else {
                $to_find[] = 'HEADER';
            }
            if (file_exists($file_base . '/footer.txt')) {
                $cruft['FOOTER'] = $this->_html_filter(file_get_contents($file_base . '/footer.txt'), $fix_html, $base_url, $files, $file_base);
            } else {
                $to_find[] = 'FOOTER';
            }
            foreach ($to_find as $template_wanted) {
                $best_ratios = array();
                foreach ($compare_file_contents as $i => $reference_file) {
                    if ($template_wanted == 'HEADER') {
                        $last_pos = strpos($reference_file, '<body');
                        if ($last_pos === false) {
                            $last_pos = 0;
                        } else {
                            $last_pos += 5;
                        }
                    } else {
                        $last_pos = strlen($reference_file) - 1;
                    }
                    $best_av_ratios = mixed();
                    $ratios = array();
                    while ($last_pos !== false) {
                        //@print('!'.(strlen($reference_file)-$last_pos).' '.$lv.' '.$ratio.'<br />'.chr(10));flush();if (@$dd++==180) @exit('fini'); // Useful for debugging
                        if ($template_wanted == 'HEADER') {
                            $next_pos = strpos($reference_file, '<', $last_pos);
                        } else {
                            $next_pos = strrpos(substr($reference_file, 0, $last_pos), '<');
                        }
                        if ($next_pos !== false) {
                            if ($template_wanted == 'HEADER') {
                                $up_to = substr($reference_file, 0, $next_pos);
                            } else {
                                $up_to = substr($reference_file, $next_pos);
                            }
                            $all_ratios_for_pos = array();
                            foreach ($compare_file_contents as $j => $other_file) {
                                if ($i != $j) {
                                    if ($template_wanted == 'HEADER') {
                                        $up_to_other_file = substr($other_file, 0, $next_pos);
                                    } else {
                                        $up_to_other_file = substr($other_file, $next_pos - (strlen($reference_file) - strlen($other_file)));
                                    }
                                    $lv = fake_levenshtein($up_to, $up_to_other_file);
                                    if ($template_wanted == 'HEADER') {
                                        $ratio = floatval($lv) * 3 - floatval($next_pos + 1);
                                        // We want this number to be as small as possible. We have multiplied the levenshtein distance because we care about that more than length (this number reached by experimentation); HTML has a low entropy which this number is fighting against.
                                    } else {
                                        $ratio = floatval($lv) * 3 - floatval(strlen($reference_file) - $next_pos);
                                        // We want this number to be as small as possible. We have multiplied the levenshtein distance because we care about that more than length (this number reached by experimentation); HTML has a low entropy which this number is fighting against.
                                    }
                                    $all_ratios_for_pos[] = $ratio;
                                }
                            }
                            $av_ratios = array_sum($all_ratios_for_pos) / floatval(count($all_ratios_for_pos));
                            if (is_null($best_av_ratios) || $av_ratios < $best_av_ratios) {
                                $best_av_ratios = $av_ratios;
                            } elseif ($av_ratios > $best_av_ratios + 300) {
                                break;
                            }
                            $ratios[$next_pos] = $av_ratios;
                            if ($template_wanted == 'HEADER') {
                                $next_pos++;
                            } else {
                                $next_pos--;
                            }
                        }
                        $last_pos = $next_pos;
                    }
                    asort($ratios);
                    $best_by_pos = array_keys($ratios);
                    $best_ratios[] = array($best_by_pos[0], $ratios[$best_by_pos[0]], $reference_file);
                }
                $best = mixed();
                $best_pos = NULL;
                $best_reference_file = NULL;
                foreach ($best_ratios as $bits) {
                    list($pos, $ratio, $reference_file) = $bits;
                    if (is_null($best) || $ratio < $best) {
                        $best = $ratio;
                        $best_pos = $pos;
                        $best_reference_file = $reference_file;
                    }
                }
                if ($template_wanted == 'HEADER') {
                    $cruft[$template_wanted] = substr($best_reference_file, 0, $best_pos);
                } else {
                    $cruft[$template_wanted] = substr($best_reference_file, $best_pos);
                }
            }
        } else {
            // We can't find any common consistency when we only have one, so we mark all cruft and then later we will actually assume GLOBAL.tpl does not change and the only header/footer bit is the logical one
            $cruft['HEADER'] = array_key_exists(0, $compare_file_contents) ? $compare_file_contents[0] : '';
            $cruft['FOOTER'] = array_key_exists(1, $compare_file_contents) ? $compare_file_contents[0] : '';
        }
        // Extract header from cruft (<body> and before); SAVE
        $header = $cruft['HEADER'];
        // special cases of something with ID or class of header/top going through too
        $header_cases = array('<div id="header"', '<div id="page_header"', '<div class="header"', '<div class="page_header"');
        foreach ($header_cases as $header_case) {
            $header_start_pos = strpos($header, $header_case);
            if ($header_start_pos !== false) {
                $header_start_pos = strpos($header, '>', $header_start_pos) + 1;
                break;
            }
        }
        if ($header_start_pos !== false) {
            $div_count = 1;
            do {
                $next_start = strpos($header, '<div ', $header_start_pos);
                $next_end = strpos($header, '</div>', $header_start_pos);
                $header_start_pos = $next_start !== false && $next_start < $next_end ? $next_start : $next_end;
                if ($header_start_pos !== false) {
                    $header_start_pos = strpos($header, '>', $header_start_pos) + 1;
                }
                $div_count += $next_start !== false && $next_start < $next_end ? 1 : -1;
            } while ($div_count > 0 && $header_start_pos !== false);
        }
        $body_start_pos = strpos($header, '<body');
        $head_end_pos = strpos($header, '<link');
        if ($head_end_pos === false) {
            $head_end_pos = strpos($header, '</head');
        }
        if ($header_start_pos === false) {
            $header_start_pos = strpos($header, '>', $body_start_pos) + 1;
        }
        if ($header_start_pos !== false) {
            $header = substr($header, 0, $header_start_pos);
        }
        $path = get_custom_file_base() . '/themes/' . filter_naughty($theme) . '/templates_custom/HEADER.tpl';
        $myfile = fopen($path, 'wt');
        $header_to_write = substr($header, 0, $head_end_pos) . '	<script type="text/javascript">// <![CDATA[
		{+START,IF,{$AND,{$EQ,,{$_GET,keep_has_js}},{$NOT,{$JS_ON}}}}
		if ((window.location.href.indexOf(\'upgrader.php\')==-1) && (window.location.search.indexOf(\'keep_has_js\')==-1)) {$,Redirect with JS on, and then hopefully we can remove keep_has_js after one click. This code only happens if JS is marked off, no infinite loops can happen.}
			window.location=window.location.href+((window.location.search==\'\')?(((window.location.href.indexOf(\'.htm\')==-1)&&(window.location.href.indexOf(\'.php\')==-1))?(((window.location.href.substr(window.location.href.length-1)!=\'/\')?\'/\':\'\')+\'index.php?\'):\'?\'):\'&\')+\'keep_has_js=1{+START,IF,{$DEV_MODE}}&keep_devtest=1{+END}\';
		{+END}
		{+START,IF,{$NOT,{$BROWSER_MATCHES,ie}}}{+START,IF,{$HAS_SPECIFIC_PERMISSION,sees_javascript_error_alerts}}window.take_errors=true;{+END}{+END}
		var {+START,IF,{$CONFIG_OPTION,is_on_timezone_detection}}server_timestamp={$FROM_TIMESTAMP%},{+END}ocp_lang=\'{$LANG;}\',ocp_theme=\'{$THEME;}\';
	//]]></script>

	<meta name="description" content="{+START,IF,{$NEQ,{DESCRIPTION},{!NA}}}{DESCRIPTION*}{+END}" />
	<meta name="keywords" content="{KEYWORDS*}" />

	{$CSS_TEMPCODE}

	{+START,IF_PASSED,EXTRA_HEAD}
		{EXTRA_HEAD}
	{+END}

	{$JS_TEMPCODE,header}

	{REFRESH}' . substr($header, $head_end_pos);
        $header_to_write = preg_replace('#<title>[^<>]*</title>#', '<title>{+START,IF_NON_EMPTY,{HEADER_TEXT}}{HEADER_TEXT*} - {+END}{$SITE_NAME*}</title>', $header_to_write);
        $header_to_write = preg_replace('#<meta name="keywords" content="([^"]*)"[^>]*>#', '', $header_to_write);
        $header_to_write = preg_replace('#<meta name="description" content="([^"]*)"[^>]*>#', '', $header_to_write);
        fwrite($myfile, $header_to_write);
        fclose($myfile);
        fix_permissions($path);
        sync_file($path);
        // Extract footer from cruft (</body> and below); SAVE
        $footer = $cruft['FOOTER'];
        // special cases of something with ID or class of footer/bottom going through too
        $footer_cases = array('<div id="footer"', '<div id="page_footer"', '<div class="footer"', '<div class="page_footer"');
        foreach ($footer_cases as $footer_case) {
            $footer_start_pos = strpos($footer, $footer_case);
            if ($footer_start_pos !== false) {
                break;
            }
        }
        if ($footer_start_pos === false) {
            $footer_start_pos = strpos($footer, '</body');
        }
        if ($footer_start_pos !== false) {
            $footer = substr($footer, $footer_start_pos);
        }
        $path = get_custom_file_base() . '/themes/' . filter_naughty($theme) . '/templates_custom/FOOTER.tpl';
        $myfile = fopen($path, 'wt');
        $footer_to_write = $footer;
        fwrite($myfile, $footer_to_write);
        fclose($myfile);
        fix_permissions($path);
        sync_file($path);
        // What remains is saved to GLOBAL (note that we don't try and be clever about panels - this is up to the user, and they don't really need them anyway)
        if (count($compare_file_contents) > 1) {
            $global_to_write = substr($cruft['HEADER'], strlen($header)) . "\n{MIDDLE}\n" . substr($cruft['FOOTER'], 0, strlen($cruft['FOOTER']) - strlen($footer));
        } else {
            $cruft['HEADER'] = $header_to_write;
            $cruft['FOOTER'] = $footer_to_write;
            $global_to_write = '{MIDDLE}';
        }
        $path = get_custom_file_base() . '/themes/' . filter_naughty($theme) . '/templates_custom/GLOBAL.tpl';
        $myfile = fopen($path, 'wt');
        fwrite($myfile, $global_to_write);
        fclose($myfile);
        fix_permissions($path);
        sync_file($path);
        // Extract site name from <title> tag, based on common consistency (largest common substring)
        $site_name = get_site_name();
        if (count($compare_file_contents) > 1) {
            $titles_in_reference_files = array();
            foreach ($compare_file_contents as $reference_file) {
                $matches = array();
                if (preg_match('#<title>(.*)</title>#', $reference_file, $matches) != 0) {
                    $titles_in_reference_files[] = $matches[1];
                }
            }
            // Find largest common substring
            $lcs = '';
            foreach ($titles_in_reference_files as $title_a) {
                for ($start = 0; $start < strlen($title_a); $start++) {
                    for ($end = $start + 1; $end < strlen($title_a); $end++) {
                        $current = substr($title_a, $start, $end - $start + 1);
                        foreach ($titles_in_reference_files as $title_b) {
                            if ($title_a != $title_b) {
                                if (strpos(strtolower($title_b), strtolower($current)) === false) {
                                    continue 2;
                                }
                            }
                        }
                        if (strpos(strtolower($title_b), strtolower($current)) !== false) {
                            if (strlen($current) > strlen($lcs)) {
                                $lcs = $current;
                            }
                        }
                    }
                }
            }
            // Strip bits
            $site_name = trim(preg_replace('#^[\\|\\-�,]#', '', preg_replace('#[\\|\\-�,]$#', '', trim($lcs))));
            // Save as site name
            set_option('site_name', $site_name);
        }
        // Go and save our pages
        disable_php_memory_limit();
        foreach ($content_files as $content_file) {
            $file_contents = file_get_contents($file_base . '/' . $content_file);
            // Find page-link for page
            $slash_count = substr_count($content_file, '/');
            if ($slash_count == 0) {
                $content_file = '/' . $content_file;
            } elseif ($slash_count > 1) {
                $last_slash_pos = strrpos($content_file, '/');
                $content_file = str_replace('/', '_', substr($content_file, 0, $last_slash_pos)) . substr($content_file, 0, $last_slash_pos);
            }
            list($zone, $page) = explode('/', preg_replace('#\\..*$#', '', $content_file), 2);
            if ($page == 'index') {
                $page = 'start';
            }
            if (substr($content_file, -4) == '.php') {
                $file_path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . '/pages/minimodules_custom/' . $page . '.php');
                $myfile = fopen($file_path, 'wt');
                fwrite($myfile, $file_contents);
                fclose($myfile);
                fix_permissions($file_path);
                sync_file($file_path);
            } else {
                $filtered = $this->_html_filter($file_contents, $fix_html, $base_url, $files, $file_base);
                // Try and work out page title from <title> tag
                $matches = array();
                $page_title = NULL;
                if (preg_match('#<title>(.*)</title>#', $filtered, $matches) != 0) {
                    $page_title = preg_replace('#( [\\|\\-�] )?' . preg_quote($site_name) . '( [\\|\\-�] )?#', '', $matches[1]);
                }
                $page_keywords = NULL;
                if (preg_match('#<meta name="keywords" content="([^"]*)"#', $filtered, $matches) != 0) {
                    $page_keywords = $matches[1];
                }
                $page_description = NULL;
                if (preg_match('#<meta name="description" content="([^"]*)"#', $filtered, $matches) != 0) {
                    $page_description = $matches[1];
                }
                require_code('seo2');
                seo_meta_set_for_explicit('comcode_page', $zone . ':' . $page, $page_keywords, $page_description);
                // Strip cruft off for htm/html files
                $i = strpos($filtered, '</head>');
                if ($i === false) {
                    $i = 0;
                } else {
                    $i += 7;
                }
                $filtered = $this->levenshtein_strip_search($cruft['HEADER'], $filtered, false, $i);
                $filtered = $this->levenshtein_strip_search($cruft['FOOTER'], $filtered, true, 0);
                // Copy htm/html/php files to correct zone page directories (html_custom/<lang>, or minimodules_custom)
                if ($convert_to_comcode == 0) {
                    // Insert an <h1> if the h1 is not there
                    if (strpos($filtered, '<h1') === false && !is_null($page_title)) {
                        $filtered = "<h1>" . $page_title . "</h1>\n\n" . $filtered;
                    }
                    $file_path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . '/pages/comcode_custom/' . get_site_default_lang() . '/' . $page . '.txt');
                    $myfile = fopen($file_path, 'wt');
                    fwrite($myfile, '[semihtml]' . $filtered . '[/semihtml]');
                    fclose($myfile);
                    fix_permissions($file_path);
                    sync_file($file_path);
                } else {
                    // Insert an <h1> if the h1 is not there
                    if (strpos($filtered, '[title') === false && !is_null($page_title)) {
                        $filtered = "[title]" . $page_title . "[/title]\n\n" . $filtered;
                    }
                    require_code('comcode_from_html');
                    $comcode = semihtml_to_comcode($filtered);
                    $file_path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . '/pages/comcode_custom/' . get_site_default_lang() . '/' . $page . '.txt');
                    $myfile = fopen($file_path, 'wt');
                    fwrite($myfile, $comcode);
                    fclose($myfile);
                    fix_permissions($file_path);
                    sync_file($file_path);
                }
            }
        }
        // Copy all remaining files to under uploads/website_specific
        foreach ($files as $file) {
            if (!file_exists($file_base . '/' . $file)) {
                continue;
            }
            $path = get_custom_file_base() . '/uploads/website_specific/' . $file;
            $create_path = $path;
            do {
                @mkdir(dirname($create_path), 0777);
                $create_path = dirname($create_path);
            } while (strlen($create_path) > 1);
            copy($file_base . '/' . $file, $path);
            fix_permissions($path);
            sync_file($path);
        }
        // Set the panels to be blank
        foreach (array('site/', '') as $zone) {
            $panels = array('panel_left', 'panel_right');
            foreach ($panels as $panel) {
                $path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . 'pages/comcode_custom/' . filter_naughty(fallback_lang()) . '/' . filter_naughty($panel) . '.txt');
                $myfile = fopen($path, 'wt');
                fclose($myfile);
                fix_permissions($path);
                sync_file($path);
            }
        }
    }
Esempio n. 13
0
/**
 * Rename a zone in the database and move any custom pages in it.
 *
 * @param  ID_TEXT		The old name of the zone
 * @param  ID_TEXT		The new name of the zone
 * @param  boolean		Whether to assume the main zone row has already been renamed as part of a wider editing operation
 */
function fu_rename_zone($zone, $new_zone, $dont_bother_with_main_row = false)
{
    if (function_exists('set_time_limit')) {
        @set_time_limit(0);
    }
    require_code('zones2');
    if (file_exists(get_file_base() . '/sources/zones3.php')) {
        require_code('zones3');
    }
    actual_rename_zone_lite($zone, $new_zone, $dont_bother_with_main_row);
    $pages = find_all_pages_wrap($zone, true, false, FIND_ALL_PAGES__ALL);
    foreach ($pages as $page => $type) {
        $path = get_file_base() . '/' . $zone . '/pages/' . $type . '/' . $page;
        $new_path = get_file_base() . '/' . $new_zone . '/pages/' . $type . '/' . $page;
        if (is_writable_wrap($path) && is_writable_wrap($new_path)) {
            rename($path, $new_path);
            sync_file_move($path, $new_path);
        }
    }
}
Esempio n. 14
0
 /**
  * This function is a very basic query executor. It shouldn't usually be used by you, as there are specialised abstracted versions available.
  *
  * @param  string			The complete SQL query
  * @param  ?integer		The maximum number of rows to affect (NULL: no limit)
  * @param  ?integer		The start row to affect (NULL: no specification)
  * @param  boolean		Whether to output an error on failure
  * @param  boolean		Whether to get an insert ID
  * @param  ?array			Extra language fields to join in for cache-prefilling. You only need to send this if you are doing a JOIN and carefully craft your query so table field names won't conflict (NULL: none)
  * @param  string			All the core fields have a prefix of this on them, so when we fiddle with language lookup we need to use this (only consider this if you're setting $lang_fields)
  * @param  boolean		Whether we are saving as a 'volatile' file extension (used in the XML DB driver, to mark things as being non-syndicated to subversion)
  * @return ?mixed			The results (NULL: no results)
  */
 function _query($query, $max = NULL, $start = NULL, $fail_ok = false, $get_insert_id = false, $lang_fields = NULL, $field_prefix = '', $save_as_volatile = false)
 {
     global $QUERY_COUNT, $NO_QUERY_LIMIT, $QUERY_LOG, $QUERY_LIST, $DEBUG_MODE, $IN_MINIKERNEL_VERSION, $QUERY_FILE_LOG, $UPON_QUERY_HOOKS;
     if ($QUERY_FILE_LOG !== NULL) {
         fwrite($QUERY_FILE_LOG, $query . ';' . chr(10) . chr(10));
     }
     if ($DEBUG_MODE) {
         if (get_forum_type() != 'none' && strpos($query, get_table_prefix() . 'f_') !== false && strpos($query, get_table_prefix() . 'f_') < 100 && strpos($query, 'f_welcome_emails') === false && $this->connection_write === $GLOBALS['SITE_DB']->connection_write && isset($GLOBALS['FORUM_DB']) && $GLOBALS['SITE_DB']->connection_write !== $GLOBALS['FORUM_DB']->connection_write && !$GLOBALS['NO_DB_SCOPE_CHECK']) {
             /*file_put_contents(get_file_base().'/uploads/downloads/test.txt',var_export(debug_backtrace(),true));
             		@exit($query);
             		@debug_print_backtrace();*/
             fatal_exit('Using OCF queries on the wrong driver');
         }
     }
     if (!$NO_QUERY_LIMIT) {
         $QUERY_COUNT++;
         //@exit('!');
         //if ($QUERY_COUNT>10) @ob_end_clean();@print('Query: '.$query.chr(10));
     }
     static $fb = NULL;
     if ($fb === NULL) {
         $fb = function_exists('fb');
     }
     if ($fb && !headers_sent() && get_param_integer('keep_firephp_queries', 0) == 1 && function_exists('fb')) {
         fb('Query: ' . $query);
     }
     if ($QUERY_COUNT == 68 && get_param_integer('keep_no_query_limit', 0) == 0 && count($_POST) == 0 && get_page_name() != 'admin_importer' && $IN_MINIKERNEL_VERSION == 0 && get_param('special_page_type', '') != 'query') {
         $NO_QUERY_LIMIT = true;
         $log_path = get_custom_file_base() . '/data_custom/big_query_screens.log';
         if (is_writable_wrap($log_path)) {
             $myfile = fopen($log_path, 'at');
             fwrite($myfile, get_self_url_easy() . chr(10));
             fclose($myfile);
         }
         if ($DEBUG_MODE) {
             $QUERY_COUNT = 0;
             fatal_exit(do_lang_tempcode('TOO_MANY_QUERIES'));
         }
     }
     $lang_strings_expecting = array();
     if (isset($lang_fields[0]) && function_exists('user_lang')) {
         $lang = user_lang();
         // We can we assume this, as we will cache against it -- if subsequently code wants something else it'd be a cache miss which is fine
         foreach ($lang_fields as $i => $field) {
             $_i = strval($i);
             $join = ' LEFT JOIN ' . $this->table_prefix . 'translate t' . $_i . ' ON t' . $_i . '.id=' . $field_prefix . $field . ' AND ' . db_string_equal_to('t' . $_i . '.language', $lang);
             $_query = strtoupper($query);
             $from_pos = strpos($_query, ' FROM ');
             $where_pos = strpos($_query, ' WHERE ');
             if ($where_pos === false) {
                 $_where_pos = 0;
                 do {
                     $_where_pos = strpos($_query, ' GROUP BY ', $_where_pos + 1);
                     if ($_where_pos !== false) {
                         $where_pos = $_where_pos;
                     }
                 } while ($_where_pos !== false);
             }
             if ($where_pos === false) {
                 $_where_pos = 0;
                 do {
                     $_where_pos = strpos($_query, ' ORDER BY ', $_where_pos + 1);
                     if ($_where_pos !== false) {
                         $where_pos = $_where_pos;
                     }
                 } while ($_where_pos !== false);
             }
             if ($where_pos !== false) {
                 $query = substr($query, 0, $where_pos) . $join . substr($query, $where_pos);
             } else {
                 $query .= $join;
             }
             $original = 't' . $_i . '.text_original AS t' . $_i . '__text_original';
             $parsed = 't' . $_i . '.text_parsed AS t' . $_i . '__text_parsed';
             $query = substr($query, 0, $from_pos) . ',' . $original . ',' . $parsed . substr($query, $from_pos);
             $lang_strings_expecting[] = array($field, 't' . $_i . '__text_original', 't' . $_i . '__text_parsed');
         }
     }
     if ($start < 0) {
         $start = 0;
     }
     if ($max < 0) {
         $max = 1;
     }
     if ($QUERY_LOG) {
         $before = microtime(false);
     }
     if (substr(strtoupper($query), 0, 7) == 'SELECT ') {
         $connection =& $this->connection_read;
     } else {
         $connection =& $this->connection_write;
     }
     if (isset($connection[4])) {
         $connection = call_user_func_array(array($this->static_ob, 'db_get_connection'), $connection);
         _general_db_init();
     }
     $ret = $this->static_ob->db_query($query, $connection, $max, $start, $fail_ok, $get_insert_id, false, $save_as_volatile);
     if ($QUERY_LOG) {
         $after = microtime(false);
         $text = !is_null($max) ? $query . ' (' . strval((int) $start) . '-' . strval((int) $start + $max) . ')' : $query;
         $out = array('time' => microtime_diff($after, $before), 'text' => $text);
         $QUERY_LIST[] = $out;
     }
     // Run hooks, if any exist
     if ($UPON_QUERY_HOOKS === NULL) {
         if (!function_exists('find_all_hooks')) {
             return $ret;
         }
         $UPON_QUERY_HOOKS = array();
         $hooks = find_all_hooks('systems', 'upon_query');
         foreach (array_keys($hooks) as $hook) {
             require_code('hooks/systems/upon_query/' . filter_naughty($hook));
             $UPON_QUERY_HOOKS[$hook] = object_factory('upon_query_' . filter_naughty($hook), true);
         }
     }
     foreach ($UPON_QUERY_HOOKS as $ob) {
         if ($ob !== NULL) {
             $ob->run($this, $query, $max, $start, $fail_ok, $get_insert_id, $ret);
         }
     }
     // Copy results to lang cache, but only if not null AND unset to avoid any confusion
     if ($ret !== NULL) {
         foreach ($lang_strings_expecting as $bits) {
             list($field, $original, $parsed) = $bits;
             foreach ($ret as $row) {
                 $entry = $row[$field];
                 if ($row[$original] !== NULL && count($this->text_lookup_original_cache) <= 1000) {
                     $this->text_lookup_original_cache[$entry] = $row[$original];
                 }
                 if ($row[$parsed] !== NULL && count($this->text_lookup_cache) <= 1000) {
                     $this->text_lookup_cache[$entry] = $row[$parsed];
                 }
                 unset($row[$original]);
                 unset($row[$parsed]);
             }
         }
     }
     return $ret;
 }
Esempio n. 15
0
/**
 * Get information for the user relating to an addon that they are intending to install.
 *
 * @param  string			Filename of the addon TAR file
 * @param  ?array			List of addons that we're currently uninstalling (so dependencies from these are irrelevant). (NULL: none)
 * @param  ?array			List of addons that we're currently installing (so dependencies to these are irrelevant). (NULL: none)
 * @return array			Triple: warnings, files, addon info array
 */
function inform_about_addon_install($file, $also_uninstalling = NULL, $also_installing = NULL)
{
    if (is_null($also_uninstalling)) {
        $also_uninstalling = array();
    }
    if (is_null($also_installing)) {
        $also_installing = array();
    }
    $full = get_custom_file_base() . '/imports/mods/' . $file;
    // Look in the tar
    require_code('tar');
    if (!file_exists($full)) {
        warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
    }
    $tar = tar_open($full, 'rb');
    $directory = tar_get_directory($tar);
    $info_file = tar_get_file($tar, 'mod.inf');
    if (is_null($info_file)) {
        warn_exit(do_lang_tempcode('NOT_ADDON'));
    }
    $info = better_parse_ini_file(NULL, $info_file['data']);
    $addon = $info['name'];
    $php = false;
    $overwrite = new ocp_tempcode();
    $dirs = array();
    $files = new ocp_tempcode();
    $files_warnings = new ocp_tempcode();
    global $M_SORT_KEY;
    $M_SORT_KEY = 'path';
    usort($directory, 'multi_sort');
    foreach ($directory as $i => $entry) {
        if ($entry['path'] == 'mod.inf') {
            continue;
        }
        if ($entry['path'] == 'mod.php') {
            continue;
        }
        if (substr($entry['path'], -1) == '/') {
            continue;
        }
        $data = strtolower(substr($entry['path'], -4, 4)) == '.tpl' ? tar_get_file($tar, $entry['path'], true) : NULL;
        // .php?
        if (strtolower(substr($entry['path'], -4, 4)) == '.php' || !is_null($data) && (strpos($data['data'], '{+START,PHP') !== false || strpos($data['data'], '<' . '?php') !== false)) {
            $php = true;
            $this_php = true;
        } else {
            $this_php = false;
        }
        // chmod?
        $pos = strrpos($entry['path'], '/');
        if ($pos !== false) {
            $dirs[substr($entry['path'], 0, $pos)] = 1;
        } else {
            $dirs[''] = 1;
        }
        // overwrite?
        if (file_exists(get_file_base() . '/' . $entry['path'])) {
            if (!$overwrite->is_empty()) {
                $overwrite->attach(do_lang_tempcode('LIST_SEP'));
            }
            $overwrite->attach(escape_html($entry['path'][0] == '/' ? substr($entry['path'], 1) : $entry['path']));
            $this_overwrite = true;
        } else {
            $this_overwrite = false;
        }
        // Comcode?
        if (strtolower(substr($entry['path'], -4, 4)) == '.txt' && strpos($entry['path'], 'pages/comcode') !== false) {
            $this_comcode_page = true;
        } else {
            $this_comcode_page = false;
        }
        // Template
        if ($this_comcode_page) {
            $files_warnings->attach(do_template('ADDON_INSTALL_FILES_WARNING', array('_GUID' => 'd0cf99f96262296df4afe2387f4cd3e8', 'I' => strval($i), 'PATH' => $entry['path'], 'ABOUT' => do_lang_tempcode('ADDON_FILE_IS_COMCODE_PAGE'))));
        } elseif ($this_overwrite) {
            $backup = substr($entry['path'], -4) == '.txt';
            $files_warnings->attach(do_template('ADDON_INSTALL_FILES_WARNING', array('_GUID' => 'c62168dee316d8f73d20a0d70d41b1a4', 'I' => strval($i), 'PATH' => $entry['path'], 'ABOUT' => do_lang_tempcode($backup ? 'ADDON_FILE_WILL_OVERWRITE_BACKUP' : 'ADDON_FILE_WILL_OVERWRITE'))));
        } elseif ($this_php) {
            $files_warnings->attach(do_template('ADDON_INSTALL_FILES_WARNING', array('_GUID' => 'c0cf99f96262296df4afe2387f4cd3e8', 'I' => strval($i), 'PATH' => $entry['path'], 'ABOUT' => do_lang_tempcode('ADDON_FILE_IS_PHP'))));
        } else {
            $files->attach(do_template('ADDON_INSTALL_FILES', array('_GUID' => '74edcf396387c842cab5cfd0ab74b8f6', 'I' => strval($i), 'PATH' => $entry['path'], 'ABOUT' => do_lang_tempcode('ADDON_FILE_NORMAL'))));
        }
    }
    tar_close($tar);
    $chmod = new ocp_tempcode();
    $root_chmod = false;
    foreach (array_keys($dirs) as $dir) {
        if (is_writable_wrap(get_file_base() . '/' . $dir) && file_exists(get_file_base() . '/' . $dir)) {
            if ($dir == '') {
                $root_chmod = true;
                continue;
            }
            if (!$chmod->is_empty()) {
                $chmod->attach(do_lang_tempcode('LIST_SEP'));
            }
            $chmod->attach(escape_html(do_lang('ROOT') . ($dir[0] != '/' ? '/' : '') . $dir));
        } elseif (substr_count($dir, '/') == 1 && !file_exists(get_file_base() . '/' . $dir)) {
            $root_chmod = true;
        }
    }
    if ($root_chmod) {
        if (!$chmod->is_empty()) {
            $chmod->attach(', ');
        }
        $chmod->attach(do_lang('ROOT'));
    }
    // Check incompatibilities, and show general warning
    // NB: It's theoretically possible that there may be incompatibilities between two addons installing together, and we can't detect this (only incompatibilities for what is already installed). However it's very unlikely as multi-install is only really going to happen with official addons which have no such problems.
    $warnings = new ocp_tempcode();
    if ($info['author'] != 'Core Team') {
        $warnings->attach(do_template('ADDON_INSTALL_WARNING', array('_GUID' => 'dd66b2c540908de60753a1ced73b8ac0', 'WARNING' => do_lang_tempcode('ADDON_WARNING_GENERAL'))));
    }
    $incompatibilities = collapse_1d_complexity('addon_name', $GLOBALS['SITE_DB']->query_select('addons_dependencies', array('addon_name'), array('addon_name_dependant_upon' => $addon, 'addon_name_incompatibility' => 1)));
    $_incompatibilities = new ocp_tempcode();
    foreach ($incompatibilities as $in) {
        if (!$_incompatibilities->is_empty()) {
            $_incompatibilities->attach(do_lang_tempcode('LIST_SEP'));
        }
        $_incompatibilities->attach(escape_html($in));
    }
    if (count($incompatibilities) != 0) {
        $warnings->attach(do_template('ADDON_INSTALL_WARNING', array('WARNING' => do_lang_tempcode('ADDON_WARNING_INCOMPATIBILITIES', $_incompatibilities))));
    }
    // Check dependencies
    $_dependencies = explode(',', array_key_exists('dependencies', $info) ? $info['dependencies'] : '');
    $dependencies = array();
    foreach ($_dependencies as $dependency) {
        if ($dependency == '') {
            continue;
        }
        if (in_array($dependency . '.tar', $also_installing)) {
            continue;
        }
        if (in_array($dependency . '.tar', $also_uninstalling)) {
            $dependencies[] = $dependency;
            continue;
        }
        if (!has_feature($dependency)) {
            $dependencies[] = $dependency;
        }
    }
    $_dependencies_str = new ocp_tempcode();
    foreach ($dependencies as $in) {
        if (!$_dependencies_str->is_empty()) {
            $_dependencies_str->attach(do_lang_tempcode('LIST_SEP'));
        }
        if (file_exists(get_custom_file_base() . '/imports/addons/' . $in . '.tar')) {
            $in_tpl = hyperlink(build_url(array('page' => 'admin_addons', 'type' => 'addon_install', 'file' => $in . '.tar'), get_module_zone('admin_addons')), $in, true, true);
        } else {
            $in_tpl = make_string_tempcode(escape_html($in));
        }
        $_dependencies_str->attach($in_tpl);
    }
    if (count($dependencies) != 0) {
        if ($info['author'] == 'Core Team') {
            $post_fields = build_keep_post_fields();
            foreach ($dependencies as $in) {
                $post_fields->attach(form_input_hidden('install_' . $in . '.tar', $in . '.tar'));
            }
            if (get_param('type', 'misc') == 'addon_install') {
                $post_fields->attach(form_input_hidden('install_' . $file, $file));
                $url = static_evaluate_tempcode(build_url(array('page' => '_SELF', 'type' => 'multi_action'), '_SELF'));
            } else {
                $url = get_self_url(true);
            }
            warn_exit(do_lang_tempcode('_ADDON_WARNING_MISSING_DEPENDENCIES', $_dependencies_str->evaluate(), escape_html($addon), array(escape_html($url), $post_fields)));
        } else {
            $warnings->attach(do_template('ADDON_INSTALL_WARNING', array('WARNING' => do_lang_tempcode('ADDON_WARNING_MISSING_DEPENDENCIES', $_dependencies_str))));
        }
    }
    //	if (!$overwrite->is_empty()) $warnings->attach(do_template('ADDON_INSTALL_WARNING',array('_GUID'=>'fe40ed8192a452a835be4c0fde64406b','WARNING'=>do_lang_tempcode('ADDON_WARNING_OVERWRITE',escape_html($overwrite)))));
    if ($info['author'] != 'Core Team') {
        if ($php) {
            $warnings->attach(do_template('ADDON_INSTALL_WARNING', array('_GUID' => '8cf249a119d10b2e97fc94cb9981dcea', 'WARNING' => do_lang_tempcode('ADDON_WARNING_PHP'))));
        }
    }
    //	if ($chmod!='') $warnings->attach(do_template('ADDON_INSTALL_WARNING',array('_GUID'=>'78121e40b9a26c2f33d09f7eee7b74be','WARNING'=>do_lan g_tempcode('ADDON_WARNING_CHMOD',escape_html($chmod))))); // Now uses AFM
    $files_combined = new ocp_tempcode();
    $files_combined->attach($files_warnings);
    $files_combined->attach($files);
    return array($warnings, $files_combined, $info);
}
Esempio n. 16
0
 /**
  * Standard modular file writing function for OcCLE FS hooks.
  *
  * @param  array	The current meta-directory path
  * @param  string	The root node of the current meta-directory
  * @param  string	The file name
  * @param  string	The new file contents
  * @param  array	A reference to the OcCLE filesystem object
  * @return boolean	Success?
  */
 function write_file($meta_dir, $meta_root_node, $file_name, $contents, &$occle_fs)
 {
     $file_name = filter_naughty($file_name);
     $path = $this->_customise_directory($meta_dir);
     if (is_dir($path) && (file_exists($path . $file_name) && is_writable_wrap($path . $file_name) || !file_exists($path . $file_name) && is_writable_wrap($path))) {
         $fh = @fopen($path . $file_name, 'wt') or intelligent_write_error($path . $file_name);
         $output = fwrite($fh, $contents);
         fclose($fh);
         if ($output < strlen($contents)) {
             warn_exit(do_lang_tempcode('COULD_NOT_SAVE_FILE'));
         }
         fix_permissions($path . $file_name);
         sync_file($path . $file_name);
         return $output;
     } else {
         return false;
     }
     //File doesn't exist
 }