Location: PHPKode > projects > ProNuke. Postnuke To Oracle > postnuke/html/mainfile2.php
<?php
// File: $Id: mainfile2.php,v 1.102 2001/12/06 19:44:09 besfred Exp $ $Name:  $
// ----------------------------------------------------------------------
// POST-NUKE Content Management System
// Copyright (C) 2001 by the Post-Nuke Development Team.
// http://www.postnuke.com/
// ----------------------------------------------------------------------
// Based on:
// PHP-NUKE Web Portal System - http://phpnuke.org/
// Thatware - http://thatware.org/
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------
// Original Author of file: Francisco Burzi
// Purpose of file:
// ----------------------------------------------------------------------

// Integration of phpAdsNew in postnuke done by Sebastien Bernard, 09/2001
// These modifications are integrated in the original GNU licence.
// phpAdsNew has to be installed before the installation of these sources in
// postnuke, unmodified, except config.inc.php, which has to be modified
// normally to allow phpadsnew to work.

// The tables has to be created separately, either in a different database,
// either in postnuke database.

define ('_mainfile_loaded', '1');
$mainfile = 1;

if (eregi('mainfile2.php', $PHP_SELF)) {
    die ("You can't access this file directly...");
}


define('ADODB_DIR', 'pnadodb');
pninclude_once("pnadodb/adodb.inc.php");
include 'config.php';


// modif sebastien multi sites
// added that defined, in order to do a multi sites' postnuke.
// each call to config.php has to be done with: include(WHERE_IS_PERSO."config.php")
// the rest will come later.
define("WHERE_IS_PERSO","");
// end of modif sebastien multi sites
if (file_exists(WHERE_IS_PERSO."pntables.php"))
    { include(WHERE_IS_PERSO."pntables.php"); }
else
    { include("pntables.php"); }



include 'modules/NS-Languages/api.php';

if ($pnconfig['encoded'] == 1){
    $connectString = "$pnconfig[dbtype]://$pnconfig[dbuname]:$pnconfig[dbpass]@$pnconfig[dbhost]/$pnconfig[dbname]";
    GLOBAL $ADODB_FETCH_MODE;
    $dbconn = &ADONewConnection($pnconfig['dbtype']);
    $dbh = $dbconn->Connect($pnconfig['dbhost'],base64_decode($pnconfig['dbuname']),base64_decode($pnconfig['dbpass']),$pnconfig['dbname']);
    $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
} else {
    $connectString = "$pnconfig[dbtype]://$pnconfig[dbuname]:$pnconfig[dbpass]@$pnconfig[dbhost]/$pnconfig[dbname]";
    GLOBAL $ADODB_FETCH_MODE;
    $dbconn = &ADONewConnection($pnconfig['dbtype']);
    $dbh = $dbconn->Connect($pnconfig['dbhost'],($pnconfig['dbuname']),($pnconfig['dbpass']),$pnconfig['dbname']);
    $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
}

 // if we get an error, log it and die
if ($dbh === false) {
    error_log ("connect string: $connectString");
    error_log ("error: " . $dbconn->ErrorMsg());
// show error and die
    PN_DBMsgError($dbconn, __FILE__ , __LINE__, "Error connecting to db".$pnconfig['dbname']);
}

//FTO Check if an oracle driver
if ( strstr('oci8,oracle,oci8po,oracle_odbc',$pnconfig['dbtype'] ) ) $oracledb=true; else $oracledb=false;

// force oracle to a consistent date format for comparison methods later on
//FTO Modified regarding all oracle drivers
if ($oracledb) {
   $dbconn->Execute("alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'");
}

// proca
// Activate dbg object if debugger is active
if ($debug){
    pninclude_once("includes/lensdebug.inc.php");
    $dbg = new LensDebug();
    $debug_sqlcalls = 0;
}

// Ensure we include the security information first,
// it has functions that the other blocks will use
pninclude_once("includes/security.php");

// from dctanner
$d = @opendir('includes/');
while ($f = @readdir($d))
{
    if (substr($f, -3, 3) == 'php')
    {
      pninclude_once("includes/$f");
    }
}
@closedir($d);

// end from dctanner

/**
 * Check if a user is an admin
 *
 * Defunct - replaced by new authorisation system but
 *           the calls are still around, so until they
 *           are removed this is a pass-through
 */
function is_admin($admin) {
    return (authorised(0, '::', '::', ACCESS_ADMIN));
}

/**
 * Checks if a user is a registered user
 *
 * This function will inspect a cookie and check if that user is a registered user
 *
 * @param $user string A user cookie
 * @return bool 1 if user is a registered user, 0 otherwise
 * @author FB
 */

function is_user($user) {
    static $is_user;
    global $pntable, $dbconn;

    if (IsSet($is_user)) return $is_user;

//FTO : unregistered by default
    $is_user = 0;
    
    if(!is_array($user)) {
        $user = base64_decode($user);
        $user = explode(':', $user);
        $uid = $user[0];
        empty($user[2]) ? $pwd = '' : $pwd = $user[2];
    } else {
        $uid = $user[0];
        $pwd = $user[2];
    }
    $column = &$pntable['users_column'];
    $result = $dbconn->Execute("SELECT $column[pass]
                              FROM $pntable[users]
                              WHERE $column[uid]='$uid'");

//FTO : Check EOF

    if (!$result->EOF)
    {
       list($pass) = $result->fields;
       if($pass == $pwd && $pass != "")$is_user = 1;
    }

    return  $is_user;
}

// Preliminary user cookie check
if (!empty($user) && (!is_user($user))) {
    setcookie("user", "", time() - 3600);
    include 'header.php';
    echo '<H1>Bad User Cookie</H1>
          You are presenting a bad user cookie.  This could
          be due to you recently changing your password and
          not accepting the new cookie, or as a result of
          a recent system upgrade.  The cookie has been
          removed from your system, so please reload and
          log in again';
    include 'footer.php';
    exit;
}

/**
 * Decode the user's cookie
 *
 * Decode the user's cookie and verify it in the database by using the
 * password. The cookie that is returned is guaranteed to be 6 elements long.
 *
 * @param $user string The user's username
 * @return array An array with the the cookie data in it
 * @author author name
 */

function cookiedecode($user) {
    global $cookie, $pntable, $dbconn;
    $user = base64_decode($user);
    $cookie = explode(':', $user);
    if (empty($cookie[1])) {
        unset($GLOBALS['cookie']);
    return;
    }
    $column = &$pntable['users_column'];
    $result = $dbconn->Execute("SELECT $column[pass]
                              FROM $pntable[users]
                              WHERE $column[uname]='$cookie[1]'");
    list($pass) = $result->fields;
    if (!empty($cookie[2]) && $cookie[2] == $pass && $pass != '') {
        return $cookie;
    } else {
        unset($user);
        // Credit to Luis Alberto Carrasco G.
        unset($GLOBALS['cookie']);
    }
}

/**
 * Get user information
 *
 * Gets user information from the database, given a cookie with user info in it.
 *
 * @param $user string User cookie
 * @return none
 * @author FB
 */

function getusrinfo($user) {
    global $userinfo, $pntable, $dbconn;

    if (empty($user)) {
       return;
    }
        if (isset($userinfo['uid'])){
           return $userinfo;
        }
    $user2 = base64_decode($user);
    $user3 = explode(":", $user2);
    $column = &$pntable['users_column'];
    $result = $dbconn->Execute("SELECT $column[uid] AS \"uid\",
                                     $column[name] AS name,
                                     $column[uname] AS uname,
                                     $column[email] AS email,
                                     $column[femail] AS femail,
                                     $column[url] AS url,
                                     $column[user_avatar] AS user_avatar,
                                     $column[user_icq] AS user_icq,
                                     $column[user_occ] AS user_occ,
                                     $column[user_from] AS user_from,
                                     $column[user_intrest] AS user_intrest,
                                     $column[user_sig] AS user_sig,
                                     $column[user_viewemail] AS user_viewemail,
                                     $column[user_theme] AS user_theme,
                                     $column[user_aim] AS user_aim,
                                     $column[user_yim] AS user_yim,
                                     $column[user_msnm] AS user_msnm,
                                     $column[pass] AS pass,
                                     $column[storynum] AS storynum,
                                     $column[umode] AS umode,
                                     $column[uorder] AS uorder,
                                     $column[thold] AS thold,
                                     $column[noscore] AS noscore,
                                     $column[bio] AS bio,
                                     $column[ublockon] AS ublockon,
                                     $column[ublock] AS ublock,
                                     $column[theme] AS theme,
                                     $column[commentmax] AS commentmax,
                                     $column[timezone_offset] AS timezone_offset
                              FROM $pntable[users]
                              WHERE $column[uname]='$user3[1]' and $column[pass]='$user3[2]'");

        // Oracle doesn't support recordcount
        //    if($result->PO_RecordCount()==1) {

        // need to fetch as just an associative array.  nobody uses the numeric

        $myuserinfo = $result->GetRowAssoc(false);
        $result->MoveNext();

        if ($result->EOF)
          {
           $userinfo = $myuserinfo;
          }
        else
          {
           echo "<font class=\"pn-title\">"._MPROBLEM."</font><br>";
          }

    return $userinfo;
}

/**
 * text filter
 */

function check_words($Message) {
    global $EditedMessage;
    include(WHERE_IS_PERSO."config.php");
    $EditedMessage = $Message;
    if ($CensorMode != 0) {

    if (is_array($CensorList)) {
        $Replace = $CensorReplace;
        if ($CensorMode == 1) {
        for ($i = 0; $i < count($CensorList); $i++) {
            $EditedMessage = eregi_replace("$CensorList[$i]([^a-zA-Z0-9])","$Replace\\1",$EditedMessage);
        }
        } elseif ($CensorMode == 2) {
        for ($i = 0; $i < count($CensorList); $i++) {
            $EditedMessage = eregi_replace("(^|[^[:alnum:]])$CensorList[$i]","\\1$Replace",$EditedMessage);
        }
        } elseif ($CensorMode == 3) {
        for ($i = 0; $i < count($CensorList); $i++) {
            $EditedMessage = eregi_replace("$CensorList[$i]","$Replace",$EditedMessage);
        }
        }
    }
    }
    return ($EditedMessage);
}

function delQuotes($string){
    // No recursive function to add quote to an HTML tag if needed
    // and delete duplicate spaces between attribs.
    $tmp="";    # string buffer
    $result=""; # result string
    $i=0;
    $attrib=-1; # Are us in an HTML attrib ?   -1: no attrib   0: name of the attrib   1: value of the atrib
    $quote=0;   # Is a string quote delimited opened ? 0=no, 1=yes
    $len = strlen($string);
    while ($i<$len) {
    switch($string[$i]) { # What car is it in the buffer ?
        case "\"": #"       # a quote.
        if ($quote==0) {
            $quote=1;
        } else {
            $quote=0;
            if (($attrib>0) && ($tmp != "")) { $result .= "=\"$tmp\""; }
            $tmp="";
            $attrib=-1;
        }
        break;
        case "=":           # an equal - attrib delimiter
        if ($quote==0) {  # Is it found in a string ?
            $attrib=1;
            if ($tmp!="") $result.=" $tmp";
            $tmp="";
        } else $tmp .= '=';
        break;
        case " ":           # a blank ?
        if ($attrib>0) {  # add it to the string, if one opened.
            $tmp .= $string[$i];
        }
        break;
        default:            # Other
        if ($attrib<0)    # If we weren't in an attrib, set attrib to 0
        $attrib=0;
        $tmp .= $string[$i];
        break;
    }
    $i++;
    }
    if (($quote!=0) && ($tmp != "")) {
    if ($attrib==1) $result .= "=";
    /* If it is the value of an atrib, add the '=' */
    $result .= "\"$tmp\"";  /* Add quote if needed (the reason of the function ;-) */
    }
    return $result;
}

/**
 * Fixes quoting on a string
 *
 * This function replaces all single single quotes with double single quotes
 * (' becomes '') and all occurrences of \' with '.
 *
 * @param $what string The string to be fixed
 * @return string The fixed string
 * @author ?
 */

function FixQuotes ($what = "") {
    $what = ereg_replace("'","''",$what);
    while (eregi("\\\\'", $what)) {
        $what = ereg_replace("\\\\'","'",$what);
    }
    return $what;
}

function check_html ($str, $strip = '') {
    // The core of this code has been lifted from phpslash
    // which is licenced under the GPL.
    include(WHERE_IS_PERSO."config.php");
    if ($strip == "nohtml")
        $AllowableHTML=array('');
    $str = stripslashes($str);
    $str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",
                         '<\\1>', $str);
// Delete all spaces from html tags .
    $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>",
                         '<a href="\\1">', $str); # "
// Delete all attribs from Anchor, except an href, double quoted.
    $tmp = "";
    while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg)) {
        $i = strpos($str,$reg[0]);
        $l = strlen($reg[0]);
        if ($reg[1][0] == "/") $tag = strtolower(substr($reg[1],1));
        else $tag = strtolower($reg[1]);
        if ($a=$AllowableHTML[$tag])
            if ($reg[1][0] == "/") $tag = "</$tag>";
            elseif (($a == 1) || ($reg[2] == "")) $tag = "<$tag>";
            else {
              # Place here the double quote fix function.
              $attrb_list=delQuotes($reg[2]);
              $tag = "<$tag" . $attrb_list . ">";
            } # Attribs in tag allowed
        else $tag = "";
        $tmp .= substr($str,0,$i) . $tag;
        $str = substr($str,$i+$l);
    }
    $str = $tmp . $str;
    return $str;
    exit;
    // Squash PHP tags unconditionally
    $str = ereg_replace("<\?","",$str);
    return $str;
}

function filter_text($Message, $strip="") {
    global $EditedMessage;
    check_words($Message);
    $EditedMessage=check_html($EditedMessage, $strip);
    return ($EditedMessage);
}

/**
 * formatting stories
 */

function formatTimestamp($time) {
    global $datetime, $locale;
    setlocale (LC_TIME, "$locale");
    // Below ereg commented out 07-08-2001:Alarion - less strict ereg thanks to "Joe"
    //ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
    ereg ("([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)", $time, $datetime);

    // 07-07-2001:Alarion - For the time being, I added an ereg_replace to strip out
    // the timezone until I get a function in to replace the server timezone with the users timezone
    $datetime = strftime("".ereg_replace("%Z", "",_DATESTRING)."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
    $datetime = ucfirst($datetime);
    return($datetime);
}

function formatAidHeader($aid) {
    global $pntable, $dbconn;
    $column = &$pntable['users_column'];
    $holder = $dbconn->Execute("SELECT $column[url], $column[email],  $column[name]
                              FROM $pntable[users]
                              WHERE $column[uid]='$aid'");
    if ($holder === false) {
        PN_DBMsgError($dbconn, __FILE__, __LINE__, "Error accesing to the database");
    }

    list($url, $email, $aid) = $holder->fields;
    if (isset($url)) {
        echo "<a href=\"$url\">$aid</a>";
    } elseif (isset($email)) {
        echo "<a class=\"pn-normal\" href=\"mailto:$email\">$aid</a>";
    } else {
        echo $aid;
    }
}

function themepreview($title, $hometext, $bodytext="", $notes="") {
    echo "<font class=\"pn-title\"><b>$title</b></font><br><br><font class=\"pn-normal\">$hometext</font>";
    if ($bodytext != "") {
        echo "<br><br><font class=\"pn-normal\">$bodytext</font>";
    }
    if ($notes != "") {
        echo "<br><br><font class=\"pn-normal\"><b>"._NOTE."</b> <i>$notes</i></font>";
    }
}

function GetUserTime($time) {
    global $userinfo, $HTTP_COOKIE_VARS, $timezone_offset;
    if(isset($HTTP_COOKIE_VARS['user'])) {
        $userinfo = getusrinfo($HTTP_COOKIE_VARS['user']);
    }
    if(!isset($HTTP_COOKIE_VARS['user'])) {
        $userszone = $timezone_offset;
    } else {
        $userszone = $userinfo['timezone_offset'];
    }
    $userszone = ($userszone - 12) * 3600;
    $tzolocal = ($timezone_offset -12) * 3600;
    $time = $time + $userszone - $tzolocal;
    return($time);
}


/**
 * Set module helper variables
 *
 * Set an array of variables to help make coding modules easer.
 * ModName   - module directory name
 * baseurl   - the begining of the url, makes coding links much easer.
 *             modules.php?op=modload&amp;name=[ModName]&amp;file=index
 * baseurl2  - the same as baseurl, except entities are not used
 *             (for header calls)
 * basepath  - the path to the module, useful for including files and
 *             for image paths
 * imagepath - path to the images directory.
 * vars      - an array of the POST and GET (url) variables, better
 *             then relying on the global versions.
 * index     - whether to display the right side blocks or not.
 * You can extract these all as globals by putting the following line
 * at the top of your module...
 * extract(modules_settings(basename(dirname(__FILE__)), true));
 *
 * @param $modulename string The module directory name
 * @param $index bool True to display right-blocks, false to hide them [optional]
 * @return an array of helper variables
 * @author Patrick Kellum <hide@address.com>
 */
function modules_settings($modulename, $index = false)
{
    if (!eregi('modules.php', $GLOBALS[PHP_SELF])){die ("You can't access this file directly...");}
    $out[ModName] = $modulename;
    $out[baseurl] = "modules.php?op=modload&amp;name=$modulename&amp;file=index";
    $out[baseurl2] = "modules.php?op=modload&name=$modulename&file=index";
    $out[basepath] = "modules/$modulename";
    $out[imagepath] = "modules/$modulename/images";
    $out[vars] = array_merge($GLOBALS[HTTP_GET_VARS], $GLOBALS[HTTP_POST_VARS]);
    $out[index] = $index;
    return $out;
}

/**
 * include_once replacement
 *
 * Works basicly like include_once() (except not
 * include() aware, I'm not sure what array name
 * they use). Needed for older PHP4 installs.
 *
 * @param $f string The file/path to include
 * @return false if file was already included. true if first include
 * @author Patrick Kellum <hide@address.com>
 */
function pninclude_once($f)
{
    static $postnuke_include_files;
    if (!empty($postnuke_include_files[$f]))
    {
        return false;
    }
    include $f;
    $postnuke_include_files[$f] = true;
    return true;
}

function myTextForm($url , $value , $useTable = false , $extraname="postnuke")
{
    $form = "";
    $form .= "<form action=\"$url\" method=\"post\">";
    if ($useTable){
        $form .= "<table border=\"0\" width=\"100%\" align=\"center\"><tr><td>\n";
    }
    $form .= "<input type=\"submit\" value=\"$value\" class=\"pn-normal\" style=\"text-align:center\">";
    $form .= "<input type=\"hidden\" name=\"$extraname\" value=\"$extraname\"></form>\n";
    if ($useTable){
        $form .= "</td></tr></table>\n";
    }
    return $form;
}

function moduleAvailable($ModName)
{
  if (file_exists("modules/$ModName"))
  {
      return true;
  } else {
      return false;
  }
}

function myImageForm($url , $imageSrc , $imageAlt , $useTable = false , $extraname="postnuke")
{
    $form = "";
    $form  .= "<form action=\"$url\" method=\"post\">\n";
    if ($useTable){
        $form .= "<table border=\"0\" width=\"100%\" align=\"center\"><tr><td>\n";
    }
    $form .= "<input type=\"image\" src=\"$imageSrc\" border=\"0\" alt=\"$imageAlt\">\n";
    $form .= "<input type=\"hidden\" name=\"$extraname\" value=\"$extraname\"></form>\n";
    if ($useTable){
        $form .= "</td></tr></table>\n";
    }
    return $form;
}

    /**
     *  Error message due a ADODB SQL error and die
     */
    function PN_DBMsgError($db='',$prg='',$line=0,$message='Error accesing to the database')
    {
        $lcmessage = $message . "<br>" .
                     "Program: " . $prg . " - " . "Line N.: " . $line . "<br>" .
                     "Database: " . $db->database . "<br> ";

        if($db->ErrorNo()<>0) {
            $lcmessage .= "Error (" . $db->ErrorNo() . ") : " . $db->ErrorMsg() . "<br>";
        }
        die($lcmessage);
    }

/**
 * get base URI for PostNuke
 * @returns string
 * @return base URI for PostNuke
 */
function pnGetBaseURI()
{
    global $HTTP_SERVER_VARS;

    // Removing trailing GET vars from path
    $path = $HTTP_SERVER_VARS['REQUEST_URI'];
    $path = preg_replace('/[#\?].*/', '', $path);
    $path = dirname($path);

    if (preg_match('!^[/\\\]*$!', $path)) {
        $path = '/';
    }

    return $path;
}

/**
 * Carry out a redirect
 * @param the URL to redirect to
 * @returns void
 */
function pnRedirect($redirecturl)
{
    global $HTTP_SERVER_VARS;

    if (preg_match('!^http!', $redirecturl)) {
        // Absolute URL - simple redirect
        Header("Location: $redirecturl");
        return;
    }

    if (empty($HTTP_SERVER_VARS['HTTP_HOST'])) {
        $server = getenv('HTTP_HOST');
    } else {
        $server = $HTTP_SERVER_VARS['HTTP_HOST'];
    }

    // Removing leading slashes from redirect url
    $redirecturl = preg_replace('!^/*!', '', $redirecturl);

    // Converting &amp; to &
    $redirecturl = preg_replace("'&(amp|#38);'","&",$redirecturl);

    $path = pnGetBaseURI();

    if ($path == '/') {
        Header("Location: http://$server/$redirecturl");
    } else {
        Header("Location: http://$server$path/$redirecturl");
    }

}

/**
 * Security upgrade.
 */
function csrfcheck() 
{
    global $HTTP_SERVER_VARS, $HTTP_HOST;

    // Get host
    $host = $HTTP_SERVER_VARS['HTTP_HOST'];
    if (empty($host)) {
        $host = $HTTP_HOST;
    }

    // Get path
    $path = $HTTP_SERVER_VARS['REQUEST_URI'];
    $path = preg_replace('/[#\?].*/', '', $path);
    $path = dirname($path);
    if (preg_match('!^[/\\\]*$!', $path)) {
        $path = '/';
    }

    // Get referer
    if (empty($HTTP_SERVER_VARS['HTTP_REFERER'])) {
        $referer = getenv('HTTP_REFERER');
    } else {
        $referer = $HTTP_SERVER_VARS['HTTP_REFERER'];
    }   

    // Glue together
    $refcheck = "$host$path";

    // Check
    if (!preg_match("!$refcheck!", $referer)) {
        die("Referer check failed - access denied");
    }
}

?>
Return current item: ProNuke. Postnuke To Oracle