Location: PHPKode > projects > Write2Left > general.php
<?php
/*
+------------------------------------------------------
| Write2Left
| (c) timdorr
| http://www.write2left.com
| hide@address.com
| See License.txt for license info
|------------------------------------------------------
| Script: general.php
| Description:
|   Contains the default set of classes to load
| Created Jun-28-03
+------------------------------------------------------
*/

/* Class: functions
 * Description:
 *   If it's a general function not specific to another class, 
 *   you'll probably fine it here
 */
class functions
{
	var $logs_sql_id = -1;
	
	//================
	// Makes sure every input we work with after this is cool
	//================
	function safe_input( $cleaner = false )
	{
		global $HTTP_CLIENT_IP, $REQUEST_METHOD, $REMOTE_ADDR, $HTTP_PROXY_USER, $HTTP_X_FORWARDED_FOR;

		$super = array( &$_GET, &$_POST, &$_COOKIE );
		
		$return = array();
		foreach( $super as $duper )
		{
			if( is_array( $duper ) )
			{
				foreach( $duper as $k => $v )
				{
					if( is_array( $duper[$k] ) )
					{
						foreach( $duper[$k] as $k2 => $v2 )
						{
							if( $cleaner )
								$return[$k][ $this->clean_key( $k2 ) ] = $this->cleaner_value( $v2 );
							else
								$return[$k][ $this->clean_key( $k2 ) ] = $this->clean_value( $v2 );
						}
					}
					else
					{
						if( $cleaner )
							$return[$k] = $this->cleaner_value( $v );
						else
							$return[$k] = $this->clean_value( $v );
					}
				}
			}
		}
		
		// Sort out the accessing IP
		
		$return['IP_ADDRESS'] = array(	1 => $HTTP_X_FORWARDED_FOR,
										2 => $HTTP_PROXY_USER,
										3 => $REMOTE_ADDR,
										4 => $_SERVER['REMOTE_ADDR']
									 );
		ksort( $return['IP_ADDRESS'] ); 	
    	$chosen = -1;
    	
    	foreach ( $return['IP_ADDRESS'] as $k => $v )
    	{
    		if ( isset( $v ) )
    		{
    			$chosen = $v;
    			break;
    		}
    	}
		
		$return['IP_ADDRESS'] = $chosen;
												 
		// Make sure we take a valid IP address
		
		$return['IP_ADDRESS'] = preg_replace( "/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", "\\1.\\2.\\3.\\4", $return['IP_ADDRESS'] );
		
		$return['REQUEST_METHOD'] = strtolower( $REQUEST_METHOD );
		
		return $return;
	}

	//================
	// Ensures input key names are kosher
	//================
    function clean_key( $key ) 
    {
    
    	if ( $key == "" )
    	{
    		return "";
    	}
    	$key = str_replace( ".."           , ""  , $key );
    	$key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
    	$key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
    	return $key;
    }
 
	//================
	// Ensures nothing goes wrong with our input values
	//================
    function clean_value( $val ) 
    {
    
    	if ( $val == "" )
    	{
    		return "";
    	}
 
		if ( get_magic_quotes_gpc() )
    	{
    		$val = stripslashes($val);
    	}
    	
    	$val = str_replace( '\\', '&#092;', $val ); // Remove user inputted backslashes
		$val = str_replace( "'" , '\\\'' , $val );
		$val = str_replace( "\"" , '\\"' , $val );

    	return $val;
    }
    
	//================
	// Mr. Sparkle!
	//================
    function cleaner_value( $val ) 
    {
    
    	if ( $val == "" )
    	{
    		return "";
    	}
    	
    	$replace = array(  "&#032;" => " ",
    					   chr(0xCA) => "",
    					   "&" => "&amp;",
    					   "<\!--" => "&#60;&#33;--",
    					   "-->" => "--&#62;",
    					   "!" => "&#33;",
    					   "'" => "&#39;",
    					   ">" => "&gt;",
    					   "<" => "&lt;",
    					   "\"" => "&quot;" );
    					   
    	$val = str_replace( array_keys( $replace ), $replace,  $val );
    	
    	$replace = array( "/<script/i" => "&#60;script",
    					  "/\|/" => "&#124;",
    					  "/\n/" => "<br>", 
    					  "/\\\$/" => "&#036;",
    					  "/\r/" => "", 
    					  "/\\\/" => "&#092;" );
    					  
    	$val = preg_replace( array_keys( $replace ), $replace,  $val );

		if ( get_magic_quotes_gpc() )
    	{
    		$val = stripslashes($val);
    	}

    	return $val;
    }
 
 
	//================
	// Creates a string of <option>'s for drop-downs
	//================
    function create_option_list( $values, $names, $selected ) 
    {
    	$output = "";
    	
    	for( $x = 0; $x < sizeof( $values ); $x++  )
    	{
    		$output .= "<option value='$values[$x]'";
    		if( $values[$x] == $selected )
    			$output .= " selected";
    		$output .= ">$names[$x]</option>\n";
    	}
    	return $output;
    }
    
	//================
	// Returns the query id of the logs this user can access
	//================
    function get_logs_sql_id()
    {
    	global $db, $userinfo;
    	
    	if( $this->logs_sql_id == -1 )
    	{
	    	$this->logs_sql_id = $db->query( "SELECT * FROM w2l_logs AS l
															LEFT JOIN w2l_editors AS a 
									    						ON l.log_id = a.log_id 
													   WHERE user_id = $userinfo->id
													   AND can_access = '1'"  );
    	}
    	
		if( $db->num_rows( $this->logs_sql_id ) != 0 )
	    	$db->data_seek( $this->logs_sql_id, 0 );
    	
    	return $this->logs_sql_id;
    }
    
	//================
	// Returns the settings for a log. Cached to reduce query count.
	//================
    function log_settings()
    {
    	global $db, $userinfo;
    	static $cache;
    	
    	if( !isset( $cache ) )
    		$cache = $db->query_fetch( "SELECT * FROM w2l_logs 
    											WHERE log_id=$userinfo->log_id" );
    											
    	return $cache;    	
    }
}


/* Class: userinfo
 * Description:
 *   Holds info about the current user
 */
class userinfo
{
	var $name		= '';
	var $id			= 0;
	var $password	= '';
	var $email		= '';
	var $ip_address	= '';
	var $session_id	= '';
	var $perms;
	var $log_id		= 0;
	var $log_name	= '';
	var $log_perms;

	function userinfo ()
	{
		global $db, $W2L, $CONFIG;
		
		$this->ip_address = $W2L->input['IP_ADDRESS'];
		
		$this->perms = array( 'can_login'	=> 0,
							  'can_logs'	=> 0,
							  'can_users'	=> 0,
							  'can_options'	=> 0,
							  'can_install'	=> 0,
							  'can_import'	=> 0 );

		$this->log_perms = array( 'can_access' 	 => 0,
								  'can_post' 	 => 0,
								  'can_edit' 	 => 0,
								  'can_upload' 	 => 0,
								  'can_config'   => 0,
								  'can_template' => 0,
								  'can_notify' 	 => 0,
								  'can_mail' 	 => 0,
								  'can_moderate' => 0 ); 

		// Are we devoid of a session? Make a new one and call them a guest
		if ( !array_key_exists( 'as', $W2L->input ) )
		{
			$this->name			= "Guest_".rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
			$this->id			= 0;
			$this->session_id	= $this->new_guest_session();

			setcookie( 'as', $this->session_id, time() + $CONFIG['session_timeout'] );
		}
		else
		{
		    // Well, we've got a session id. Lets see if it's legal...
			$this->validate_session( $W2L->input['as'] );
		}
	}

	//================
	// Creates a new session for guests
	//================
	function new_guest_session()
	{
		global $db, $W2L;

		$new_session_id = md5( uniqid( microtime() ) );

		$db->query( "INSERT INTO w2l_sessions VALUES (
						'".$new_session_id."', 
						'".$this->name."', 
						0, 
						'',
						'',
						'".serialize( $this->perms )."',
						0,
						'',
						'".serialize( $this->log_perms )."',
						'".$this->ip_address."',
						'".$W2L->time_now."',
						'".$W2L->time_now."', 
						'')" );

		return $new_session_id;
	}

	//================
	// Upgrades our session from guest to user
	//================
	function convert_guest_session( $user_name, $user_id, $user_pass, $user_email, $user_perms )
	{
		global $db, $W2L;

		$db->query( "UPDATE w2l_sessions SET
						user_name='$user_name',
						user_id='$user_id',
						user_pass='$user_pass',
						user_email='$user_pass',
						user_perms='".serialize( $user_perms )."',
						last_time=".$W2L->time_now.",
						last_action='".$W2L->input['Action']."'
						WHERE sid='$this->session_id'" );
						
		$this->name		= $user_name;
		$this->id		= $user_id;
		$this->email	= $user_email;
		$this->perms	= $user_perms;
	}

	//================
	// Checks to make sure our session is one that exists and is correct
	//================
	function validate_session( $session_id )
	{
		global $W2L, $db, $CONFIG;
        
        // Is the the session in the db?
		$validate_result = $db->query( "SELECT * FROM w2l_sessions WHERE sid='$session_id'" );

        // If so, get the data and store the cookie
		if ( $db->num_rows( $validate_result ) == 1 ) 
		{
			$user_data = $db->fetch_array( $validate_result );
			
			$this->name			= $user_data['user_name'];
			$this->id			= $user_data['user_id'];
			$this->email		= $user_data['user_email'];
			$this->perms		= unserialize($user_data['user_perms']);
			$this->session_id	= $session_id;
			$this->log_id		= $user_data['log_id'];
			$this->log_name		= $user_data['log_name'];
			$this->log_perms	= unserialize($user_data['log_perms']);
			
			// Double check on login abilty, and lock them out now if they can't..
			if( $this->perms['can_login'] == 0 )
				$this->id = 0;

			setcookie( 'as', $this->session_id, time() + $CONFIG['session_timeout'] );
		}
		// Or else we're still a guest...
		else
		{
			$this->name			= "Guest_".rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
			$this->id			= 0;
			$this->session_id	= $this->new_guest_session();

			setcookie( 'as', $this->session_id, time() + $CONFIG['session_timeout'] );
		}
	}

	//================
	// Updates a session
	//================
	function update_session( $session_id )
	{
		global $db, $W2L;

		if( array_key_exists( 'new_log_id', $W2L->input ) && $this->id != 0)
		{
			$this->log_id = $W2L->input['new_log_id'];
			$log_info = $db->query_fetch( "SELECT name FROM w2l_logs WHERE log_id={$this->log_id}" );
			$this->log_name = $log_info['name'];
			
			$editor_info = $db->query_fetch( "SELECT * FROM w2l_editors 
													   WHERE log_id={$this->log_id}
													   	 AND user_id={$this->id}" );
			$this->log_perms =
					 array( 'can_access' 	=> $editor_info['can_access'],
							'can_post' 		=> $editor_info['can_post'],
							'can_edit' 		=> $editor_info['can_edit'],
							'can_upload' 	=> $editor_info['can_upload'],
							'can_config' 	=> $editor_info['can_config'],
							'can_template'	=> $editor_info['can_template'],
							'can_notify' 	=> $editor_info['can_notify'],
							'can_mail' 		=> $editor_info['can_mail'],
							'can_moderate' 	=> $editor_info['can_moderate'] ); 
		}

		$db->query( "UPDATE w2l_sessions SET
						last_time={$W2L->time_now},
						last_action='{$W2L->input['Action']}',
						log_id={$this->log_id},
						log_name='{$this->log_name}',
						log_perms='".serialize($this->log_perms)."'
						WHERE sid='$session_id'" );
	}
	
	//================
	// Removes our current session
	//================
	function remove_session()
	{
		global $db;

		$db->query( "DELETE FROM w2l_sessions WHERE sid='$this->session_id'" );
	}
}

/* Class: display
 * Description:
 *   Responsible for printing to our user. 
 *   This class should be the only way things get on screen.
 */
class display
{
	var $html		= "";
	var $loc		= "";
	var $menu_html	= "";
	var $skin_main	= "";
	var $page_title	= "";

	function display()
	{
		global $W2L, $userinfo;
		
		// Load the main skin file
		require( "./Skin/Skin.php" );
		$this->skin_main = new Skin();
		
		// Start our breadcrumb trail...
		$this->loc = "<a href='index.php' class='header'>Home</a>";

		$system_actions =  array( 'Main',
								  'Weblogs',
								  'Users',
								  'Options',
								  'Import' ) ;

		if( !in_array( $W2L->input['Action'], $system_actions )
		 && $userinfo->log_id != 0 )
		{
			$this->loc .= " &gt; <a href='index.php?Action=Log' class='header'>{$userinfo->log_name}</a>";
		}
	}

	//================
	// A simple addition to the output
	//================
	function add( $output = "" )
	{
		$this->html .= $output;
		return true;
	}
	
	//================
	// Adds to our location 
	//================
	function loc_add( $addition = "" )
	{
		$this->loc .= " > " . $addition;
		return true;
	}
	
	//================
	// Sets up the menu - Will be more dynamic in the future...
	//================
	function menu_set()
	{
		global $W2L, $db, $userinfo, $func;

		if( $userinfo->log_id != 0 && $W2L->input['Action'] != 'Main' )
		{
			$this->menu_html .= "<big>$userinfo->log_name</big><br />";
			
			if( $userinfo->log_perms['can_post'] == 1 )
			{
				$this->menu_html .= '<small>Posting:</small><br />';
				$this->menu_html .= '&raquo; <a href="index.php?Action=NewPost">New Post</a><br />';
				if( $userinfo->log_perms['can_edit'] == 1 )
				{				
					$this->menu_html .= '&raquo; <a href="index.php?Action=EditPosts">Manage</a><br />';
					$this->menu_html .= '&raquo; <a href="index.php?Action=FindPosts">Search</a><br />';
				}
				if( $userinfo->log_perms['can_config'] == 1 )
					$this->menu_html .= '&raquo; <a href="index.php?Action=Cats">Categories</a><br />';
				$this->menu_html .= '<br />';
			}

			if( $userinfo->log_perms['can_template'] == 1 )
			{
				$this->menu_html .= '<small>Templating:</small><br />';
				$this->menu_html .= '&raquo; <a href="index.php?Action=Templates">Templates</a><br />';
				/* To be completed ;) $this->menu_html .= '&raquo; <a href="index.php?Action=Blocks">Blocks</a><br />'; */
				$this->menu_html .= '&raquo; <a href="index.php?Action=Rebuild">Rebuild</a><br />';
				$this->menu_html .= '<br />';
			}
			
			$this->menu_html .= '<small>Other:</small><br />';
			if( $userinfo->log_perms['can_config'] == 1 )
			{
				$this->menu_html .= '&raquo; <a href="index.php?Action=Config">Settings</a><br />';
				$this->menu_html .= '&raquo; <a href="index.php?Action=Plugins">Plugins</a><br />';
			}
			if( $userinfo->log_perms['can_notify'] == 1 )
				$this->menu_html .= '&raquo; <a href="index.php?Action=Subs">Subscriptions</a><br />';
			$this->menu_html .= '&raquo; <a href="index.php?Action=Export">Export</a><br />';
			$this->menu_html .= '&raquo; <a href="index.php?Action=View" target="_blank">View Log</a><br />';
			$this->menu_html .= '<br />';
		}
		
		$id = $func->get_logs_sql_id();
		if( $db->num_rows( $id ) > 0 )
		{
			$action = $W2L->input['Action'];
			if( $W2L->input['Action'] == 'Main' )
				$action = 'Log';
			$this->menu_html .= "<big>Weblogs:</big><br />";
			$this->menu_html .= "<select name=\"new_log_id\" onchange=\"if(this.options[this.selectedIndex].value != -1){ window.location='index.php?Action=$action&new_log_id='+this.value; }\">";
			$this->menu_html .= "<option value='-1'>Switch Weblog</option><option value='-1'>--------</option>";
			while( $log = $db->fetch_array( $id ) )
			{
				$this->menu_html .= "<option value='$log[log_id]'>$log[name]</option>";
			}
		
			$this->menu_html .= "</select><br /><br />";
		}

		$this->menu_html .= "<big>System</big><br />";
		
		$this->menu_html .= '<small>General:</small><br />';
		if( $userinfo->perms['can_logs'] == 1 )
			$this->menu_html .= '&raquo; <a href="index.php?Action=Weblogs">Weblogs</a><br />';
		if( $userinfo->perms['can_users'] == 1 )
			$this->menu_html .= '&raquo; <a href="index.php?Action=Users">Users</a><br />';
		if( $userinfo->perms['can_options'] == 1 )
			$this->menu_html .= '&raquo; <a href="index.php?Action=Options">Options</a><br />';
		if( $userinfo->perms['can_install'] == 1 )
			$this->menu_html .= '&raquo; <a href="index.php?Action=Installer">Installer</a><br />';
		if( $userinfo->perms['can_import'] == 1 )
			$this->menu_html .= '&raquo; <a href="index.php?Action=Import">Import</a><br />';
		
		$this->menu_html .= '<br />';

		$this->menu_html .= '&raquo; <a href="index.php?Action=Logout">Logout</a><br />';
		return true;
	}

	//================
	// Sends all our data stored for output to the browser
	//================
	function do_output()
	{
		global $W2L, $db, $userinfo, $driver;

		$this->menu_set();
		
		$old_html = $this->html;
		
		// Don't show the username/logout if we're not logged in
		$name = "";
		if( $userinfo->id != 0 )
			$name = $userinfo->name . " - <a href='index.php?Action=Logout' class='header'>Logout</a>";
		
		$error = '';
		if( $W2L->errors != "" )
		{
			$error = <<<EOF
<link rel="stylesheet" href="./Skin/files/main.css" type="text/css" />
<div class="error" style="margin: 10px;">
<big><b>PHP Error</b></big><br />
<br />
A php system error occured. 
This is most likely due to a bug in the Write2Left code.
Please email the following info and a detailed description 
of what occured to 
<a href="mailto:hide@address.com">hide@address.com</a>.
<br /><br />
<textarea rows="10" style="width:450px">
EOF;
			$error .= $W2L->errors;
			$error .= '</textarea></div>';
		}

		$this->html  = $this->skin_main->page_head( $this->page_title, 
													$this->loc, 
													$name,
													$error); 
		if( $driver->menu )
			$this->html .= $this->skin_main->menu( $this->menu_html );
		$this->html .= $old_html;
		$this->html .= $this->skin_main->page_foot();

		// Close our DB connection
		$db->close();
		
		// Enable gzip if it's set on
		if ( $W2L->settings['enable_gzip'] == 1 )
        {
        	ob_start ( 'ob_gzhandler' );
        }

		print $this->html;
		
		//We shouldn't be printing after this (unless debugging), so halt execution
		if( !array_key_exists( 'debug', $W2L->input ) && $W2L->settings['debug'] != 1 )
			exit;
	}
}

?>
Return current item: Write2Left