<?php 


// pppBlog
// ------------------------------
// Based on Simple PHP blog and TFT gallery
// Joerg Tiedemann, jorgen <at> gmx.net
//	
// pppBlog is released under the GNU Public License.
//

global $default_permissions;

$default_permissions = array(
    'comment' => 1,
    'add' => 1,
    'edit' => 1,
    'delete' => 0,
    'move' => 0,
    'setup' => 0,
    'upload' => 0,
    'create_album' => 0,
    'edit_album' => 0,
    'send_album' => 0
    );

$admin_permissions = array(
    'comment' => 1,
    'add' => 1,
    'edit' => 1,
    'delete' => 1,
    'move' => 1,
    'setup' => 1,
    'upload' => 1,
    'create_album' => 1,
    'edit_album' => 1,
    'send_album' => 1
    );


function convert_passfile() {
  if (file_exists('config/password.txt')){
    $hashed = sb_read_file( 'config/password.txt' );
    $result = sb_write_file( 'config/admin.php',"<?php \$admin_auth='".$hashed."';?>" );
    unlink ('config/password.txt');
    return $result;
  }
  return false;
} 
	
function logged_in ( $redirect_to_login, $redirect_to_setup ) {
  // Check if the user is logged in and has a session.
  //
  // Session data is stored in a client-side cookie.
  // Login flag is stored in the session cookie.

  // Support for PHP >= 4.1.0
  // Check if the user has a client-side cookie.

  global $signed_in;

  if ( isset( $_COOKIE[ 'my_id' ] ) ) {
    $my_id = $_COOKIE[ 'my_id' ];
			
    // Turn off URL SIDs.
    // ini_set( 'session.use_trans_sid', '0' );

    if ( !session_id() ) {						
      // Init the session.
      session_set_cookie_params(time()+60*60*24*7);
      session_id($my_id);
      session_start ();
    }
  }
			
  // Check if they're logged in.
  if ( isset( $_SESSION[ 'logged_in' ] ) && $_SESSION[ 'logged_in' ] == 'yes' ) {
    if ( $_SESSION[ 'site_path' ] === dirname($_SERVER[ 'PHP_SELF' ]) ) {
      global $blog_permissions;
      global $admin_permissions;
      $blog_permissions=$admin_permissions;
      $signed_in = true;
      return ( true );
    }
  }

  //  $signed_in = signed_in( $redirect_to_login, $redirect_to_setup );
  $signed_in = signed_in();

  // Special Case:
  // If there's no password file then need to redirect them.
  $passFile = 'config/admin.php';
  if ( !file_exists( $passFile ) ) {
    convert_passfile();
  }
		
  if ( !file_exists( $passFile ) ) {
    if ( $redirect_to_setup ) {
      redirect_to_url( 'install00.php' );      
      exit;
    } else {
      return ( -1 );
    }
  }
		
  if ( $redirect_to_login ) {
    redirect_to_url( 'index.php' );    
    exit;
  } else {
    return ( false );
  }
}



//function signed_in ( $redirect_to_login, $redirect_to_setup ) {
function signed_in ( ) {
  // Check if the user is signed in and has a session.
  //
  // Session data is stored in a client-side cookie.
  // Signin flag is stored in the session cookie.

  // Support for PHP >= 4.1.0
  // Check if the user has a client-side cookie.

  global $signed_in;

  if ( isset( $_COOKIE[ 'my_id' ] ) ) {
    $my_id = $_COOKIE[ 'my_id' ];
			
    // Turn off URL SIDs.
    // ini_set( 'session.use_trans_sid', '0' );

    if ( !session_id() ) {			
      // Init the session.
      session_set_cookie_params(time()+60*60*24*7);
      session_id($my_id);
      session_start ();
    }
  }
			
  // Check if they're logged in.
  if ( isset( $_SESSION[ 'signed_in' ] ) && 
       $_SESSION[ 'signed_in' ] == 'yes' ) {
    if ( $_SESSION[ 'site_path' ] === dirname($_SERVER[ 'PHP_SELF' ]) ) {
      global $default_permissions;
      global $blog_permissions;
      if (file_exists('config/permissions.php')){
	global $all_permissions;
	require('config/permissions.php');
	if (array_key_exists('__DEFAULT__',$all_permissions)){
	  foreach ($all_permissions['__DEFAULT__'] as $key => $val){
	    $default_permissions[$key] = $val;
	  }
	  // $default_permissions = $all_permissions['__DEFAULT__'];
	}
	if (array_key_exists($_SESSION['user'],$all_permissions)){
	  $blog_permissions = $all_permissions[$_SESSION['user']];
	}
	else{
	  $blog_permissions = $default_permissions;
	}
      }
      else{
	$blog_permissions = $default_permissions;
      }
      $signed_in = true;
      return ( true );
    }
  }
  return ( false );
  //  return logged_in ( $redirect_to_login, $redirect_to_setup );
}


function set_permissions(&$permissions){

    $filename = 'config/permissions.php';
    if (file_exists($filename)){chmod($filename,0644);}

    $string = "<?php \nglobal \$all_permissions;\n";
    foreach ($permissions as $user => $perm){
	foreach ($perm as $task => $enabled){
	    $user = str_replace("'",'',$user);
	    $task = str_replace("'",'',$task);
	    $string .= "\$all_permissions['$user']['$task'] = $enabled;\n";
	}
    }
    $string .= ' ?>';
    $result = sb_write_file($filename,$string);

    if (file_exists($filename)){
	chmod($filename,0444);
    }
}


	
function logout () {
  // Log Out
  //
  // Support for PHP >= 4.1.0
  if ( isset( $_COOKIE[ 'my_id' ] ) ) {
    $my_id = $_COOKIE[ 'my_id' ];
			
    // Turn off URL SIDs.
    // ini_set( 'session.use_trans_sid', '0' );
			
    // Init the session.
    session_set_cookie_params(time()+60*60*24*7);
    session_id($my_id);
    session_start();
    if (isset($_SESSION['signed_in'])){
      session_unset($_SESSION[ 'signed_in' ]);
    }
    else{
      session_unset($_SESSION[ 'logged_in' ]);
    }
    session_unset($_SESSION[ 'site_path' ]);
    session_unset($_SESSION[ 'user' ]);
    session_destroy();
  }
}



//////////////////////////////////////////////////////////
// joerg 2005/09/11 change password (only when logged_in)

function change_password ( $user,$pass ){
  global $logged_in;
  $logged_in = logged_in( true, true );  // do this again just in case
  $filename = 'config/admin.php';
  if (file_exists($filename)){
    if (chmod($filename,0644)){


      // Generate and store password hash
      //
      $mypasswd = $user.$pass;
      $hashed = crypt($mypasswd); 

      // Save File
      $filename = 'config/admin.php';
      $result = sb_write_file($filename,"<?php \$admin_auth='".$hashed."';?>");

      // password file read only!
      if (file_exists($filename)){
	chmod($filename,0444);
      }		
      if ( $result ) {
	// Start Session and Set Cookie
	// ini_set( 'session.use_trans_sid', '0' );
	session_set_cookie_params(time()+60*60*24*7);
	@session_start();
			
	// Support for PHP >= 4.1.0
	$_SESSION[ 'logged_in' ] = 'yes';
	$_SESSION[ 'site_path' ] = dirname($_SERVER[ 'PHP_SELF' ]);
	setcookie('my_id',session_id(),time()+60*60*24*7);
			
	return ( true );
      }
    }
    return false;
  }
}
//////////////////////////////////////////////////////////


	
function create_password ( $user, $pass ) {
  // Generate and store password hash
  //
  $mypasswd = $user.$pass;
  $hashed = crypt($mypasswd); 

  // Save File
  $filename = 'config/admin.php';

  //////////////////////////////////////////////////////////////
  // joerg, 2005/09/11 --> return false if file exists already!
  // (create password is only allowed once!

  if (file_exists($filename)){return false;}

  $result = sb_write_file( $filename,"<?php \$admin_auth='".$hashed."';?>" );

  ////////////////////////////////////////////////
  // joerg, 2005/09/11 --> password file read only!
  
  if (file_exists($filename)){
    chmod($filename,0444);
  }
		
  if ( $result ) {
    // Start Session and Set Cookie
    // ini_set( 'session.use_trans_sid', '0' );
    session_set_cookie_params(time()+60*60*24*7);
    @session_start();
			
    // Support for PHP >= 4.1.0
    $_SESSION[ 'logged_in' ] = 'yes';
    $_SESSION[ 'site_path' ] = dirname($_SERVER[ 'PHP_SELF' ]);
    setcookie('my_id',session_id(),time()+60*60*24*7);
			
    return ( true );
  } else {
    // Error:
    // Probably couldn't create file...
    return ( $filename );
  }
}



// create new user

function create_user ( $username, $password ) {
  // Generate and store password hash for a new user
  //

  $username = str_replace("'",'',$username);
  if (!strlen($username)){
    return "Please specify a username!";
  }
  if (!strlen($password)){
    return "Please type a password!";
  }

  // Save File
  $filename = 'config/user.php';

  $user = array();
  if (file_exists($filename)){
    include($filename);
    if (isset($user[$username])){
      return "Username '".$username."' exists already!";
    }
    chmod($filename,0644);
  }
  for ($i=1;$i<5;$i++){
    $fh = fopen($filename,'a+');
    if ($fh){
      flock( $fh, LOCK_EX );
      break;
    }
    sleep(1);
  }

  if ($fh){
    $mypasswd = $username.$password;
    $hashed = crypt($mypasswd); 
    $str = "<?php \$user['".$username."'] = '".$hashed."'; ?>\n";
    $result = fwrite( $fh, $str );
    $lock = flock( $fh, LOCK_UN );
    fclose( $fh );
    if (file_exists($filename)){
      chmod($filename,0444);
    }
  }
  if ($result){
    return "User '".$username."' successfully created!";
  }
  return "Failed to create user '".$username."'!";
}


// validate user


function validate_user ($code){
  global $lang_string;

  if (!strlen($code)) return false;

  $filename = 'config/signup_request.php';
  $user = array();
  $pass = array();
  if (file_exists($filename)){
    include($filename);
    if (isset($user[$code])){
      if (isset($pass[$code])){
	$username = $user[$code];

	$filename = 'config/user.php';

	$user = array();
	if (file_exists($filename)){
	  include($filename);
	  if (isset($user[$username])){
	    return "Username '".$username."' exists already!";
	  }
	  chmod($filename,0644);
	}
	for ($i=1;$i<5;$i++){
	  $fh = fopen($filename,'a+');
	  if ($fh){
	    flock( $fh, LOCK_EX );
	    break;
	  }
	  sleep(1);
	}

	if ($fh){
	  $hashed = $pass[$code];
	  $str = "<?php \$user['".$username."'] = '".$hashed."'; ?>\n";
	  $result = fwrite( $fh, $str );
	  $lock = flock( $fh, LOCK_UN );
	  fclose( $fh );
	  if (file_exists($filename)){
	    chmod($filename,0444);
	  }
	}
	if ($result){
	  return "User '".$username."' successfully created!";
	}
	return "Failed to create user '".$username."'!";

	//	return create_user($user[$code],$pass[$code]);
      }
    }
  }
  return false;
}



function signup_request ( $username, $password ) {
  // Generate and store password hash for a new user
  //
  global $lang_string;

  $username = str_replace("'",'',$username);

  if (!preg_match('/^[a-zA-Z0-9\_\-\.]+\@[a-zA-Z0-9\_\-\.]+$/',$username)){
    echo $lang_string['invalid_username'];
    return false;
  }

  if (!strlen($username)){
    echo $lang_string['invalid_username'];
    return false;
  }
  if (!strlen($password)){
    $lang_string['invalid_password'];
    return false;
  }

  $filename = 'config/user.php';
  $user = array();
  if (file_exists($filename)){
    include($filename);
    if (isset($user[$username])){
      echo "Username '".$username."' exists already!";
      return false;
    }
  }

  // Save File
  $filename = 'config/signup_request.php';

  if (file_exists($filename)){
    include($filename);
    if (isset($user[$username])){
      echo "Username '".$username."' exists already!";
      return false;
    }
    chmod($filename,0644);
  }

  for ($i=1;$i<5;$i++){
    $fh = fopen($filename,'a+');
    if ($fh){
      flock( $fh, LOCK_EX );
      break;
    }
    sleep(1);
  }

  if ($fh){
    $capcha = sb_get_capcha();
    $mypasswd = $username.$password;
    $hashed = crypt($mypasswd);
    $code = $username.$capcha;
    $str = "<?php \$user['".$code."'] = '".$username."'; ?>\n";
    $str .= "<?php \$pass['".$code."'] = '".$hashed."'; ?>\n";
    $result = fwrite( $fh, $str );
    $lock = flock( $fh, LOCK_UN );
    fclose( $fh );
    if (file_exists($filename)){
      chmod($filename,0444);
    }
  }
  if ($result){
    //    $validate_script = $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
    $validate_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    $validate_script = 
      str_replace('/signup.php','/validate.php',$validate_script);
    $validate_script .= '?code='.urlencode($code);

    global $blog_config;
    $message = "\nWelcome to ".$blog_config['blog_title']."!\n\n";
    $message .= "Please validate your username and password at \n";
    $message .= $validate_script;
    $message .= "\n\n";
    if (mail($username,'Validate your username and password',$message)){
      echo $lang_string['signup_request_ok'];
      return true;
    }
    else{
	echo "Couldn't send mail to '$username'<br />";
    }
  }
  echo $lang_string['signup_request_failed'];
  return false;
}


	
function check_password ( $user, $pass ) {
  // Check password against hashed password file
  //
  $passFile = 'config/admin.php';
  include($passFile);
  $hashed = $admin_auth; 
		
  // Verify Password
  $mypasswd = $user.$pass;
  $chkpass = crypt($mypasswd, $hashed); 
  if ($hashed === $chkpass) { 
    // Start Session and Set Cookie
    // ini_set( 'session.use_trans_sid', '0' );
    session_set_cookie_params(time()+60*60*24*7);
    @session_start();
			
    // Support for PHP >= 4.1.0
    $_SESSION[ 'logged_in' ] = 'yes';
    $_SESSION[ 'site_path' ] = dirname($_SERVER[ 'PHP_SELF' ]);
    $_SESSION[ 'user' ] = $user;
    setcookie('my_id',session_id(),time()+60*60*24*7);
			
    return ( true );
  } else { 
    return ( false );
  }
}


function check_user_password ( $username, $password ) {
  // Check password against hashed password file
  //

  $username = str_replace("'",'',$username);

  $user = array();
  $passFile = 'config/user.php';
  if (file_exists($passFile)){
    include($passFile);
  }

  if (!isset($user[$username])) return false;

  // Verify Password
  $mypasswd = $username.$password;
  $chkpass = crypt($mypasswd, $user[$username]); 
  if ($user[$username] === $chkpass) { 
    // Start Session and Set Cookie
    // ini_set( 'session.use_trans_sid', '0' );
    session_set_cookie_params(time()+60*60*24*7);
    @session_start();
			
    // Support for PHP >= 4.1.0
    $_SESSION[ 'signed_in' ] = 'yes';
    $_SESSION[ 'site_path' ] = dirname($_SERVER[ 'PHP_SELF' ]);
    $_SESSION[ 'user' ] = $username;
    setcookie('my_id',session_id(),time()+60*60*24*7);
			
    return ( true );
  } else { 
    return ( false );
  }
}



	
function redirect_to_url( $relative_url = 'index.php' ) {
  if ( ( dirname($_SERVER[ 'PHP_SELF' ]) == '\\' || 
	 dirname($_SERVER[ 'PHP_SELF' ]) == '/' ) ) {
    // Hosted at root.
    header('Location: http://'.$_SERVER[ 'HTTP_HOST' ].'/'.$relative_url);
  } else {
    // Hosted in sub-directory.
    header('Location: http://'.$_SERVER[ 'HTTP_HOST' ].dirname($_SERVER[ 'PHP_SELF' ]).'/'.$relative_url);
  }
  exit;
}
?>
