• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Beta - but working - code for a new and extensive Session Library.

#1
[eluser]starbbs[/eluser]
Some time ago i tried to convert cakes session lib to ci. It's not done, but most of it works. You can replace this lib with the original session library.Maybe it will inspire someone to get ideas or to finish it ? It has a LOT of options and it;s working excellent

Code:
<?php
define('MIB_SESSION_SAVE', 'php');
define('MIB_SECURITY', 'medium');
define('MIB_SESSION_TIMEOUT', '10');
define('MIB_SESSION_STRING', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');
define('LOG_ERROR', 2);

class CI_Session{
var $maxTime;
var $sessionTime = false;
var $time = false;
var $lastError = null;
var $path = false;
var $error = false;
var $valid = false;
var $security = null;
var $lasterror = null;

function CI_Session($start = true){
  if($start === true){
   $this->CI = & get_instance();
   $this->__active = $start;

   $this->tablename = 'ci_sessions';
   $this->host = $_SERVER['HTTP_HOST'];
   $this->ip_address = $_SERVER['REMOTE_ADDR'] ;
   $this->path = $this->CI->config->item('sess_cookie_path');

   if (empty($this->path)){
$this->path = '/';
   }
   if (strpos($this->host, ':') !== false){
$this->host = substr($this->host, 0, strpos($this->host, ':'));
   }
   if (mibGetParam($_SERVER, 'HTTP_USER_AGENT') != null){
$this->userAgent = mibGetParam($_SERVER, 'HTTP_USER_AGENT');
   }else{
$this->userAgent = 'Empty';
   }
   $this->time = $this->get_correct_time();
   $this->sessionlength = $this->CI->config->item('sess_expiration');
   $this->sessionTime = $this->time + ($this->inactiveMins() * MIB_SESSION_TIMEOUT);
   $this->security = MIB_SECURITY;

   if (function_exists('session_write_close')){
session_write_close();
   }

   $this->__initSession();

   session_cache_limiter ("must-revalidate");
   session_start();
   header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');

   $this->__checkValid();

   $start = false;
  }
  // parent::__construct();
}

function get_correct_time(){
  /**
   * Set the "now" time
   *
   * It can either set to GMT or time(). The pref
   * is set in the config file.  If the developer
   * is doing any sort of time localization they
   * might want to set the session time to GMT so
   * they can offset the "last_activity" and
   * "last_visit" times based on each user's locale.
   */
  if (strtolower($this->CI->config->item('time_reference')) == 'gmt'){
   $now = time();
   $this->now = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));

   if (strlen($this->now) < 10){
$this->now = time();
log_message('error', 'The session class could not set a proper GMT timestamp so the local time() value was used.');
   }
  }else{
   $this->now = time();
  }
}

function inactiveMins(){
  // $security =& Security::getInstance();
  switch (MIB_SECURITY){
   case 'high':
return 10;
break;
   case 'medium':
return 100;
break;
   case 'low':
   default :
return 300;
break;
  }
}

function __initSession(){
  switch(MIB_SECURITY){
   case 'high':
$this->cookieLifeTime = 0;
if (function_exists('ini_set')){
  ini_set('session.referer_check', $this->host);
}
break;
   case 'medium':
$this->cookieLifeTime = 7 * 86400;
break;
   case 'low':
   default:
$this->cookieLifeTime = 788940000;
break;
  }

  if (!isset($_SESSION)){
   if (function_exists('ini_set')){
ini_set('session.use_trans_sid', 0);
ini_set('url_rewriter.tags', '');
ini_set('session.save_handler', 'user');
ini_set('session.serialize_handler', 'php');
ini_set('session.use_cookies', 1);
ini_set('session.name', $this->CI->config->item('sess_cookie_name'));
ini_set('session.cookie_lifetime', $this->cookieLifeTime);
ini_set('session.cookie_path', $this->path);
ini_set('session.gc_probability', 5);
ini_set('session.auto_start', 0);
   }
   session_set_save_handler(array($this, '__open'),
array($this, '__close'),
array($this, '__read'),
array($this, '__write'),
array($this, '__destroy'),
array($this, '__gc'));
  }
}

function isValid(){
  return $this->valid;
}

function readSessionVar($name = null){
  if (is_null($name)){
   return $this->returnSessionVars();
  }
  if ($this->checkSessionVar($name)){
   $result = eval("return " . $this->__sessionVarNames($name) . ";");
   return $result;
  }
  $this->__setError(2, "$name doesn't exist");
  $return = null;
  return $return;
}
/**
  * Writes value to given session variable name.
  * @param mixed $name
  * @param string $value
  * @return void
  */
function writeSessionVar($name, $value){
  $expression = $this->__sessionVarNames($name);
  $expression .= " = \$value;";
  eval ($expression);
}
// continue next page

#2
[eluser]starbbs[/eluser]
Code:
function __sessionVarNames($name){
  if (is_string($name)){
   if (strpos($name, ".")){
    $names = explode(".", $name);
   }else{
    $names = array($name);
   }
   $expression = "\$_SESSION";

   foreach($names as $item){
    $expression .= is_numeric($item) ? "[$item]" : "['$item']";
   }
   return $expression;
  }
  $this->__setError(3, "$name is not a string");
  return false;
}

function checkSessionVar($name){
  $expression = "return isset(" . $this->__sessionVarNames($name) . ");";
  return eval($expression);
}

function returnSessionVars(){
  if (!empty($_SESSION)){
   $result = eval("return \$_SESSION;");
   return $result;
  }
  $this->__setError(2, "No Session vars set");
  return false;
}

function destroyInvalid(){
  $sessionpath = session_save_path();
  $cookiename = $this->CI->config->item('sess_cookie_name');
  if (empty($sessionpath)){
   $sessionpath = "/tmp";
  }

  if (isset($_COOKIE[session_name()])){
   setcookie($cookiename, '', time() - 42000, $this->path);
  }
  $file = $sessionpath . '/' . "sess_" . session_id();
  @session_destroy();
  @unlink ($file);
  $this->__construct();
  $this->renew();
}

function getError($errorNumber){
  if (!is_array($this->error) || !array_key_exists($errorNumber, $this->error)){
   return false;
  }else{
   return $this->error[$errorNumber];
  }
}

function getLastError(){
  if ($this->lastError){
   return $this->getError($this->lastError);
  }else{
   return false;
  }
}

function __setError($errorNumber, $errorMessage){
  if ($this->error === false){
   $this->error = array();
  }
  $this->error[$errorNumber] = $errorMessage;
  $this->lastError = $errorNumber;
}

function __checkValid(){
  if ($this->readSessionVar("Config")){
   if ($this->userAgent == $this->readSessionVar("Config.userAgent") && $this->time <= $this->readSessionVar("Config.time")){
    $this->writeSessionVar("Config.time", $this->sessionTime);
    $this->valid = true;
   }else{
    $this->valid = false;
    $this->__setError(1, "Session Highjacking Attempted !!!");
    $this->destroyInvalid();
   }
  }else{
   srand ((double)microtime() * 1000000);
   $this->writeSessionVar('Config.rand', rand());
   $this->writeSessionVar("Config.time", $this->sessionTime);
   $this->writeSessionVar("Config.userAgent", $this->userAgent);
   $this->writeSessionVar("Config.ip_address", $this->ip_address);
   $this->writeSessionVar("schoolnaam", 'test naampje');
   $this->valid = true;

   $this->userdata = array('session_id' => md5(uniqid(session_id(), true)),
    'ip_address' => $this->CI->input->ip_address(),
    'user_agent' => substr($this->CI->input->user_agent(), 0, 50),
    'last_activity' => $this->now);

   $this->CI->db->query($this->CI->db->insert_string('ci_sessions', $this->userdata));

   $this->userdata['last_visit'] = 0;
   $this->__setError(1, "Session is valid");
  }
}

function __open(){
  return true;
}

function __close(){
  return true;
}

/**
  * Get the number of online users
  *
  * @return integer number of users currently online
  */
function get_all_users_online(){
  // counts the rows from the database
  $result = mysql_fetch_assoc(mysql_query("SELECT COUNT(session_id) as count FROM ci_sessions"));
  // return the number of found rows
  return $result["count"];
}

/**
  * Custom gc() function (garbage collector)
  *
  * @access private
  */
function __gc(){
  srand(time());
  if ((rand() % 100) < get_cfg_var('session.gc_probability')){
   $expire = $this->now - $this->sessionlength;

   $this->CI->db->where("last_activity < {$expire}");
   $this->CI->db->delete($this->session_table);

   log_message('debug', 'Session garbage collection performed.');
  }

  $expiry_time = time() - $this->sessionTime;
  log_message('debug', "SESSION DB -> The garbage collector was launched $expiry_time");
  $CI = & get_instance();
  // it deletes expired sessions from database
  $CI->db->query("DELETE FROM ci_sessions WHERE expires <= $expiry_time");
}

function __read ($id){
  $allData = array();
  $hasData = false;
  $result = false;
  log_message('debug', "Trying to read $id from SESSION DB");
  $this->CI->db->select('val');
  $this->CI->db->from($this->tablename);
  $this->CI->db->where('id', $id);
  $result = $this->CI->db->get($this->tablename);
  $frecords = $result->num_rows();
  if($frecords > 1){
   $hasData = ($frecords > 1) ? true : false;
   $allData[] = $result->result_array();
   log_message('debug', "Succesfully found $frecords in the SESSION db for $id");
  }
  if ($hasData){
   log_message('debug', "It seems that 'hasData' var was set to true because it found records in the session db");
   return $allData[$id];
  }else{
   log_message('debug', "No data has been found in de SESSION db for $id");
   return '';
  }
}

// continue next page

#3
[eluser]starbbs[/eluser]
Code:
function renew(){
  $this->__regenerateId();
}

function __regenerateId(){
  $oldSessionId = session_id();
  $sessionpath = session_save_path();
  $cookiename = $this->CI->config->item('sess_cookie_name');

  if (empty($sessionpath)){
   $sessionpath = "/tmp";
  }

  if (isset($_COOKIE[session_name()])){
   setcookie($cookiename, '', time() - 42000, $this->path);
  }
  session_regenerate_id();
  $newSessid = session_id();
  $file = $sessionpath . '/' . "sess_$oldSessionId";
  @unlink ($file);
  @session_destroy ($oldSessionId);

  if (function_exists('session_write_close')){
   session_write_close();
  }
  $this->__initSession();
  session_id ($newSessid);
  session_start();
}

function __write($key, $value){
  log_message('debug', "__WRITE key $key - value $value");

  switch(MIB_SECURITY){
   case 'high':
    $factor = 10;
    break;
   case 'medium':
    $factor = 100;
    break;
   case 'low':
    $factor = 300;
    break;
   default:
    $factor = 10;
    break;
  }
  $CI = & get_instance();
  $expires = time() + MIB_SESSION_TIMEOUT * $factor;
  $results = $CI->db->query("SELECT COUNT(id) AS count FROM ci_sessions WHERE id = '" . $key . "'");
  $row_count = $results->num_rows();
  log_message('debug', "__WRITE No rows were found");

  if ($row_count > 1){
   $data1 = array('val' => $value,
    'expires' => $expires);

   $CI->db->where('id', $key);
   $CI->db->update('ci_sessions', $data1);
  }else{
   /**
    * $data2 = array( 'data' => $value,
    * 'expires'=> $expires,
    * 'id' => $key);
    *
    * $this->CI->db->insert($this->tablename, $data2);
    */
   $sql = "INSERT INTO ci_sessions (val,expires,id) VALUES ('$value','$expires','$key')";
   $CI->db->query($sql);
   // echo "INSERTED $sql found records:".$CI->db->affected_rows();
  }
  return true;
}

/**
  * Fetch a specific item form  the session array
  *
  * @access public
  * @param string $
  * @return string
  */
function userdata($item){
  return (! isset($this->userdata[$item])) ? false : $this->userdata[$item];
}
// --------------------------------------------------------------------
/**
  * Add or change data in the "userdata" array
  *
  * @access public
  * @param mixed $
  * @param string $
  * @return void
  */
function set_userdata($newdata = array(), $newval = ''){
  if (is_string($newdata)){
   $newdata = array($newdata => $newval);
  }

  if (count($newdata) > 0){
   foreach ($newdata as $key => $val){
    $this->userdata[$key] = $val;

    $this->writeSessionVar($key, $val);
   }
  }

  $this->renew();
}

function delSessionVar($name){
  if ($this->checkSessionVar($name)){
   $var = $this->__sessionVarNames($name);
   eval ("unset($var);");
   return true;
  }
  $this->__setError(2, "$name doesn't exist");
  return false;
}
// --------------------------------------------------------------------
/**
  * Delete a session variable from the "userdata" array
  *
  * @access array
  * @return void
  */
function unset_userdata($newdata = array()){
  if (is_string($newdata)){
   $newdata = array($newdata => '');
  }

  if (count($newdata) > 0){
   foreach ($newdata as $key => $val){
    $this->delSessionVar($key);
    unset($this->userdata[$key]);
   }
  }
}

/**
  * Sets session attributes to the given values
  */
function set($newkey, $newval){
  log_message('debug', 'Session SET with key ' . $newkey . ' with value ' . $newval . '');

  if (is_string($newkey) AND is_string($newval)){
   $this->writeSessionVar($newkey, $newval);
  }

  $newdata = array($newval);

  log_message('debug', "Problem with the SESSION lib. Cannot find an array $newdata,$newval");

  $this->writeSessionVar($newkey[0], $newdata);

  return;
}

function __destroy ($id){
  $id = int($id);
  log_message('debug', "The _destroy function is called for id ($id). Let's clean the SESSION");
  // $db->execute("DELETE FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key, 'integer'));
  $this->CI->db->delete($this->tablename, array('session_id' => $id));
  return $true;
}

// continue next page

#4
[eluser]starbbs[/eluser]
Code:
function check_activity(){
  // it selects the field nick (which is the only one to be displayd) and then it filters for 1 day or less in age of activity. after that, it filters for 5 minutes or less in activity.
  // first you need to filter away the other days, or your script might get fooled to think that yesterdays login was todays.
  // SELECT nick FROM `users` WHERE TO_DAYS( NOW( ) ) - TO_DAYS( last_login ) <=1 AND DATE_FORMAT( CURRENT_TIMESTAMP( ) , '%H%i' ) - DATE_FORMAT( last_login, '%H%i' ) <=5 ORDER BY `nick` ASC;
}

/**
  * Get the number of online users
  *
  *   This is not 100% accurate. It depends on how often the garbage collector is run
  *
  * @return integer approximate number of users currently online
  */
function get_users_online(){
  // counts the rows from the database
  $result = $CI->db->query('SELECT COUNT(session_id) as count FROM ' . $this->tablename . '');
  // return the number of found rows
  return $result["count"];
}

/**
  * Enter description here...
  *
  * Use like this. $this->Session->setFlash('This has been saved');
  *
  * @param string $flashMessage Message to be flashed
  * @param string $layout Layout to wrap flash message in
  * @param array $params Parameters to be sent to layout as view variables
  * @param string $key Message key, default is 'flash'
  * @return string Last session error
  */
function setFlash($flashMessage, $layout = 'default', $params = array(), $key = 'flash'){
  if ($layout == 'default'){
   $out = '<div id="' . $key . 'Message" class="message">' . $flashMessage . '</div>';
  }else if($layout == '' || $layout == null){
   $out = $flashMessage;
  }else{
   $ctrl = null;
   $view = new View($ctrl);
   $view->base = $this->base;
   $view->webroot = $this->webroot;
   $view->here = $this->here;
   $view->params = $this->params;
   $view->action = $this->action;
   $view->val = $this->val;
   $view->plugin = $this->plugin;
   $view->helpers = array('Html');
   $view->layout = $layout;
   $view->pageTitle = '';
   $view->_viewVars = $params;
   $out = $view->renderLayout($flashMessage);
  }
  $this->write('Message.' . $key, $out);
}
/**
  * Use like this. $this->Session->flash();
  *
  * @param string $key Optional message key
  * @return null
  */
function flash($key = 'flash'){
  if ($this->check('Message.' . $key)){
   e($this->read('Message.' . $key));
   $this->del('Message.' . $key);
  }else{
   return false;
  }
}
}

?&gt;

Thats it... your guruus can figure this out

#5
[eluser]carnalito[/eluser]
Hi starbbs,

it don't work:

Code:
Fatal error: Call to undefined function mibgetparam() in /home/app/libraries/ci_session.php on line 35

Regards

Carnalito


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.