Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Mon, Jan 6, 12:22 AM

in-portal

Index: branches/5.2.x/core/kernel/session/session.php
===================================================================
--- branches/5.2.x/core/kernel/session/session.php (revision 15516)
+++ branches/5.2.x/core/kernel/session/session.php (revision 15517)
@@ -1,1104 +1,1091 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/*
The session works the following way:
1. When a visitor loads a page from the site the script checks if cookies_on varibale has been passed to it as a cookie.
2. If it has been passed, the script tries to get Session ID (SID) from the request:
3. Depending on session mode the script is getting SID differently.
The following modes are available:
- Session::smAUTO
Automatic mode: if cookies are on at the client side, the script relays only on cookies and
ignore all other methods of passing SID. If cookies are off at the client side, the script relays on SID
passed through query string and referal passed by the client. THIS METHOD IS NOT 100% SECURE, as long as
attacker may get SID and substitude referal to gain access to user' session. One of the faults of this method
is that the session is only created when the visitor clicks the first link on the site, so there
is NO session at the first load of the page. (Actually there is a session, but it gets lost after
the first click because we do not use SID in query string while we are not sure if we need it)
- Session::smCOOKIES_ONLY
Cookies only: in this mode the script relays solely on cookies passed from the browser and ignores
all other methods. In this mode there is no way to use sessions for clients without cookies support
or cookies support disabled. The cookies are stored with the full domain name and path to base-directory
of script installation.
- Session::smGET_ONLY
GET only: the script will not set any cookies and will use only SID passed in query string using GET,
it will also check referal. The script will set SID at the first load of the page
- Session::smCOOKIES_AND_GET
Combined mode: the script will use both cookies and GET right from the start. If client has cookies enabled,
the script will check SID stored in cookie and passed in query string, and will use this SID only if both
cookie and query string matches. However if cookies are disabled on the client side, the script will work
the same way as in GET_ONLY mode.
4. After the script has the SID it tries to load it from the Storage (default is database)
5. If such SID is found in the database, the script checks its expiration time. If session is not expired,
it updates its expiration, and resend the cookie (if applicable to session mode)
6. Then the script loads all the data (session variables) pertaining to the SID.
Usage:
$session = new Session(Session::smAUTO); //Session::smAUTO is default, you could just leave the brackets empty, or provide another mode
$session->SetCookieDomain('my.domain.com');
$session->SetCookiePath('/myscript');
$session->SetCookieName('my_sid_cookie');
$session->SetGETName('sid');
$session->InitSession();
...
//link output:
echo "<a href='index.php?'". ( $session->NeedQueryString() ? 'sid='.$session->SID : '' ) .">My Link</a>";
*/
class Session extends kBase {
const smAUTO = 1;
const smCOOKIES_ONLY = 2;
const smGET_ONLY = 3;
const smCOOKIES_AND_GET = 4;
var $Checkers;
var $Mode;
var $OriginalMode = null;
var $GETName = 'sid';
var $CookiesEnabled = true;
var $CookieName = 'sid';
var $CookieDomain;
var $CookiePath;
var $CookieSecure = 0;
var $SessionTimeout = 3600;
var $Expiration;
var $SID;
var $CachedSID;
var $SessionSet = false;
/**
* Session ID is used from GET
*
* @var bool
*/
var $_fromGet = false;
/**
* Enter description here...
*
* @var SessionStorage
* @access protected
*/
protected $Storage;
var $CachedNeedQueryString = null;
/**
* Session Data array
*
* @var Params
*/
var $Data;
/**
* Names of optional session keys with their optional values (which does not need to be always stored)
*
* @var Array
*/
var $OptionalData = Array ();
/**
* Session expiration mark
*
* @var bool
*/
var $expired = false;
/**
* Creates session
*
* @param int $mode
* @access public
*/
public function __construct($mode = self::smAUTO)
{
parent::__construct();
$this->SetMode($mode);
}
function SetMode($mode)
{
$this->Mode = $mode;
$this->CachedNeedQueryString = null;
$this->CachedSID = null;
}
function SetCookiePath($path)
{
$this->CookiePath = str_replace(' ', '%20', $path);
}
/**
* Setting cookie domain. Set false for local domains, because they don't contain dots in their names.
*
* @param string $domain
*/
function SetCookieDomain($domain)
{
// 1. localhost or other like it without "." in domain name
if (!substr_count($domain, '.')) {
// don't use cookie domain at all
$this->CookieDomain = false;
return ;
}
// 2. match using predefined cookie domains from configuration
$cookie_domains = $this->Application->ConfigValue('SessionCookieDomains');
if ($cookie_domains) {
$cookie_domains = array_map('trim', explode("\n", $cookie_domains));
foreach ($cookie_domains as $cookie_domain) {
if (ltrim($cookie_domain, '.') == $domain) {
$this->CookieDomain = $cookie_domain; // as defined in configuration
return ;
}
}
}
// 3. only will execute, when none of domains were matched at previous step
$this->CookieDomain = $this->_autoGuessDomain($domain);
}
/**
* Auto-guess cookie domain based on $_SERVER['HTTP_HOST']
*
* @param $domain
* @return string
*/
function _autoGuessDomain($domain)
{
static $cache = Array ();
if (!array_key_exists($domain, $cache)) {
switch ( substr_count($domain, '.') ) {
case 2:
// 3rd level domain (3 parts)
$cache[$domain] = substr($domain, strpos($domain, '.')); // with leading "."
break;
case 1:
// 2rd level domain (2 parts)
$cache[$domain] = '.' . $domain; // with leading "."
break;
default:
// more then 3rd level
$cache[$domain] = ltrim($domain, '.'); // without leading "."
break;
}
}
return $cache[$domain];
}
function SetGETName($get_name)
{
$this->GETName = $get_name;
}
function SetCookieName($cookie_name)
{
$this->CookieName = $cookie_name;
}
function InitStorage($special)
{
$this->Storage = $this->Application->recallObject('SessionStorage.'.$special);
$this->Storage->setSession($this);
}
public function Init($prefix, $special)
{
parent::Init($prefix, $special);
if ( php_sapi_name() == 'cli' ) {
$this->SetMode(self::smGET_ONLY);
}
$this->CheckIfCookiesAreOn();
if ($this->CookiesEnabled) $_COOKIE['cookies_on'] = 1;
$this->Checkers = Array();
$this->InitStorage($special);
$this->Data = new Params();
$tmp_sid = $this->GetPassedSIDValue();
$check = $this->Check();
if ($this->Application->isAdmin) {
// 1. Front-End session may not be created (SID is present, but no data in database).
// Check expiration LATER from kApplication::Init, because template, used in session
// expiration redirect should be retrieved from mod-rewrite url first.
// 2. Admin sessions are always created, so case when SID is present,
// but session in database isn't is 100% session expired. Check expiration
// HERE because Session::SetSession will create missing session in database
// and when Session::ValidateExpired will be called later from kApplication::Init
// it won't consider such session as expired !!!
$this->ValidateExpired();
}
if ($check) {
$this->SID = $this->GetPassedSIDValue();
$this->Refresh();
$this->LoadData();
}
else {
$this->SetSession();
}
if (!is_null($this->OriginalMode)) $this->SetMode($this->OriginalMode);
}
function ValidateExpired()
{
if (defined('IS_INSTALL') && IS_INSTALL) {
return ;
}
// $this->DeleteExpired(); // called from u:OnDeleteExpiredSessions scheduled task now
if ($this->expired || ($this->CachedSID && !$this->_fromGet && !$this->SessionSet)) {
$this->RemoveSessionCookie();
// true was here to force new session creation, but I (kostja) used
// RemoveCookie a line above, to avoid redirect loop with expired sid
// not being removed setSession with true was used before, to set NEW
// session cookie
$this->SetSession();
// case #1: I've OR other site visitor expired my session
// case #2: I have no session in database, but SID is present
$this->expired = false;
$this->Application->HandleEvent(new kEvent('u:OnSessionExpire'));
}
}
/**
* Helper method for detecting cookie availability
*
* @return bool
*/
function _checkCookieReferer()
{
// removing /admin for compatability with in-portal (in-link/admin/add_link.php)
$path = preg_replace('/admin[\/]{0,1}$/', '', $this->CookiePath);
$reg = '#^'.preg_quote(PROTOCOL.ltrim($this->CookieDomain, '.').$path).'#';
return preg_match($reg, getArrayValue($_SERVER, 'HTTP_REFERER') );
}
function CheckIfCookiesAreOn()
{
if ( $this->Mode == self::smGET_ONLY ) {
//we don't need to bother checking if we would not use it
$this->CookiesEnabled = false;
return false;
}
$http_query = $this->Application->recallObject('HTTPQuery');
/* @var $http_query kHTTPQuery */
$cookies_on = array_key_exists('cookies_on', $http_query->Cookie); // not good here
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ( ($this->Application->HttpQuery->IsHTTPSRedirect() && $get_sid) || $this->getFlashSID() ) { // Redirect from http to https on different domain OR flash uploader
$this->OriginalMode = $this->Mode;
$this->SetMode(self::smGET_ONLY);
}
if ( !$cookies_on || $this->Application->HttpQuery->IsHTTPSRedirect() || $this->getFlashSID() ) {
//If referer is our server, but we don't have our cookies_on, it's definetly off
$is_install = defined('IS_INSTALL') && IS_INSTALL;
if ( !$is_install && $this->_checkCookieReferer() && !$this->Application->GetVar('admin') && !$this->Application->HttpQuery->IsHTTPSRedirect() ) {
$this->CookiesEnabled = false;
}
else {
//Otherwise we still suppose cookies are on, because may be it's the first time user visits the site
//So we send cookies on to get it next time (when referal will tell us if they are realy off
$this->SetCookie('cookies_on', 1, adodb_mktime() + 31104000); //one year should be enough
}
}
else {
$this->CookiesEnabled = true;
}
return $this->CookiesEnabled;
}
/**
* Sets cookie for current site using path and domain
*
* @param string $name
* @param mixed $value
* @param int $expires
*/
function SetCookie($name, $value, $expires = null)
{
if (isset($expires) && $expires < adodb_mktime()) {
unset($this->Application->HttpQuery->Cookie[$name]);
}
else {
$this->Application->HttpQuery->Cookie[$name] = $value;
}
$old_style_domains = Array (
// domain like in pre 5.1.0 versions
'.' . SERVER_NAME,
// auto-guessed domain (when user specified other domain in configuration variable)
$this->_autoGuessDomain(SERVER_NAME)
);
foreach ($old_style_domains as $old_style_domain) {
if ($this->CookieDomain != $old_style_domain) {
// new style cookie domain -> delete old style cookie to prevent infinite redirect
setcookie($name, $value, adodb_mktime() - 3600, $this->CookiePath, $old_style_domain, $this->CookieSecure);
}
}
setcookie($name, $value, $expires, $this->CookiePath, $this->CookieDomain, $this->CookieSecure);
}
function Check()
{
// don't check referer here, because it doesn't provide any security option and can be easily falsified
$sid = $this->GetPassedSIDValue();
if (empty($sid)) {
return false;
}
//try to load session by sid, if everything is fine
$result = $this->LoadSession($sid);
$this->SessionSet = $result; // fake front-end session will given "false" here
return $result;
}
function LoadSession($sid)
{
if( $this->Storage->LocateSession($sid) ) {
// if we have session with such SID - get its expiration
$this->Expiration = $this->Storage->GetExpiration();
// If session has expired
if ($this->Expiration < adodb_mktime()) {
// when expired session is loaded, then SID is
// not assigned, but used in Destroy method
$this->SID = $sid;
$this->Destroy();
$this->expired = true;
// when Destory methods calls SetSession inside and new session get created
return $this->SessionSet;
}
// Otherwise it's ok
return true;
}
else {
// fake or deleted due to expiration SID
if (!$this->_fromGet) {
$this->expired = true;
}
return false;
}
}
function getFlashSID()
{
$http_query = $this->Application->recallObject('HTTPQuery');
/* @var $http_query kHTTPQuery */
return getArrayValue($http_query->Post, 'flashsid');
}
function GetPassedSIDValue($use_cache = 1)
{
if (!empty($this->CachedSID) && $use_cache) {
return $this->CachedSID;
}
// flash sid overrides regular sid
$get_sid = $this->getFlashSID();
if (!$get_sid) {
$http_query = $this->Application->recallObject('HTTPQuery');
/* @var $http_query kHTTPQuery */
$get_sid = getArrayValue($http_query->Get, $this->GETName);
}
$sid_from_get = $get_sid ? true : false;
if ($this->Application->GetVar('admin') == 1 && $get_sid) {
$sid = $get_sid;
}
else {
switch ($this->Mode) {
case self::smAUTO:
//Cookies has the priority - we ignore everything else
$sid = $this->CookiesEnabled ? $this->GetSessionCookie() : $get_sid;
if ($this->CookiesEnabled) {
$sid_from_get = false;
}
break;
case self::smCOOKIES_ONLY:
$sid = $this->GetSessionCookie();
break;
case self::smGET_ONLY:
$sid = $get_sid;
break;
case self::smCOOKIES_AND_GET:
$cookie_sid = $this->GetSessionCookie();
//both sids should match if cookies are enabled
if (!$this->CookiesEnabled || ($cookie_sid == $get_sid)) {
$sid = $get_sid; //we use get here just in case cookies are disabled
}
else {
$sid = '';
$sid_from_get = false;
}
break;
}
}
$this->CachedSID = $sid;
$this->_fromGet = $sid_from_get;
return $this->CachedSID;
}
/**
* Returns session id
*
* @return int
* @access public
*/
function GetID()
{
return $this->SID;
}
/**
* Generates new session id
*
* @return int
* @access private
*/
function GenerateSID()
{
- list ($usec, $sec) = explode(' ', microtime());
-
- $sid_part_1 = substr($usec, 4, 4);
- $sid_part_2 = mt_rand(1, 9);
- $sid_part_3 = substr($sec, 6, 4);
- $digit_one = substr($sid_part_1, 0, 1);
-
- if ($digit_one == 0) {
- $digit_one = mt_rand(1, 9);
- $sid_part_1 = preg_replace('/^0/', '', $sid_part_1);
- $sid_part_1 = $digit_one . $sid_part_1;
- }
-
- $this->setSID($sid_part_1 . $sid_part_2 . $sid_part_3);
+ $this->setSID(kUtil::generateId());
return $this->SID;
}
/**
* Set's new session id
*
* @param int $new_sid
* @access private
*/
function setSID($new_sid)
{
$this->SID /*= $this->CachedSID*/ = $new_sid; // don't set cached sid here
$this->Application->SetVar($this->GETName,$new_sid);
}
function NeedSession()
{
$data = $this->Data->GetParams();
$data_keys = array_keys($data);
$optional_keys = array_keys($this->OptionalData);
$real_keys = array_diff($data_keys, $optional_keys);
return $real_keys ? true : false;
}
function SetSession($force = false)
{
if ( $this->SessionSet && !$force ) {
return true;
}
$this->Expiration = adodb_mktime() + $this->SessionTimeout;
if ( !$force && /*!$this->Application->isAdmin &&*/ !$this->Application->GetVar('admin') && !$this->NeedSession() ) {
// don't create session (in db) on Front-End, when sid is present (GPC), but data in db isn't
if ( $this->_fromGet ) {
// set sid, that was given in GET
$this->setSID($this->GetPassedSIDValue());
}
else {
// re-generate sid only, when cookies are used
$this->GenerateSID();
}
$this->Storage->StoreSession(false);
return false;
}
if ( !$this->SID || $force ) {
$this->GenerateSID();
}
switch ( $this->Mode ) {
case self::smAUTO:
if ( $this->CookiesEnabled ) {
$this->SetSessionCookie();
}
break;
case self::smGET_ONLY:
break;
case self::smCOOKIES_ONLY:
case self::smCOOKIES_AND_GET:
$this->SetSessionCookie();
break;
}
$this->Storage->StoreSession();
if ( $this->Application->isAdmin || $this->Special == 'admin' ) {
$this->StoreVar('admin', 1);
}
$this->SessionSet = true; // should be called before SaveData, because SaveData will try to SetSession again
if ( $this->Special != '' ) {
// front-session called from admin or otherwise, then save it's data
$this->SaveData();
}
$this->Application->resetCounters('UserSessions');
return true;
}
/**
* Returns SID from cookie.
*
* Use 2 cookies to have 2 expiration:
* - 1. for normal expiration when browser is not closed (30 minutes by default), configurable
* - 2. for advanced expiration when browser is closed
*
* @return int
*/
function GetSessionCookie()
{
$keep_session_on_browser_close = $this->Application->ConfigValue('KeepSessionOnBrowserClose');
if (isset($this->Application->HttpQuery->Cookie[$this->CookieName]) &&
( $keep_session_on_browser_close ||
(
!$keep_session_on_browser_close &&
isset($this->Application->HttpQuery->Cookie[$this->CookieName.'_live'])
&&
$this->Application->HttpQuery->Cookie[$this->CookieName] == $this->Application->HttpQuery->Cookie[$this->CookieName.'_live']
)
)
) {
return $this->Application->HttpQuery->Cookie[$this->CookieName];
}
return false;
}
/**
* Updates SID in cookie with new value
*
*/
function SetSessionCookie()
{
$this->SetCookie($this->CookieName, $this->SID, $this->Expiration);
$this->SetCookie($this->CookieName.'_live', $this->SID);
$_COOKIE[$this->CookieName] = $this->SID; // for compatibility with in-portal
}
function RemoveSessionCookie()
{
$this->SetCookie($this->CookieName, '');
$this->SetCookie($this->CookieName.'_live', '');
$_COOKIE[$this->CookieName] = null; // for compatibility with in-portal
}
/**
* Refreshes session expiration time
*
* @access private
*/
function Refresh()
{
if ($this->Application->GetVar('skip_session_refresh')) {
return ;
}
if ($this->CookiesEnabled) {
// we need to refresh the cookie
$this->SetSessionCookie();
}
$this->Storage->UpdateSession();
}
function Destroy()
{
$this->Storage->DeleteSession();
$this->Data = new Params();
$this->SID = $this->CachedSID = '';
$this->SessionSet = false;
if ($this->CookiesEnabled) {
$this->SetSessionCookie(); //will remove the cookie due to value (sid) is empty
}
$this->SetSession(true); //will create a new session, true to force
}
function NeedQueryString($use_cache = 1)
{
if ($this->CachedNeedQueryString != null && $use_cache) {
return $this->CachedNeedQueryString;
}
$result = false;
switch ($this->Mode) {
case self::smAUTO:
if (!$this->CookiesEnabled) {
$result = true;
}
break;
/*case self::smCOOKIES_ONLY:
break;*/
case self::smGET_ONLY:
case self::smCOOKIES_AND_GET:
$result = true;
break;
}
$this->CachedNeedQueryString = $result;
return $result;
}
function LoadData()
{
$this->Data->AddParams( $this->Storage->LoadData() );
}
function PrintSession($comment = '')
{
if (defined('DEBUG_MODE') && $this->Application->isDebugMode() && kUtil::constOn('DBG_SHOW_SESSIONDATA')) {
// dump session data
$this->Application->Debugger->appendHTML('SessionStorage [' . ($this->RecallVar('admin') == 1 ? 'Admin' : 'Front-End') . '] ('.$comment.'):');
$session_data = $this->Data->GetParams();
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (kUtil::IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
if (!$this->RecallVar('admin')) {
// dump real keys (only for front-end)
$data_keys = array_keys($session_data);
$optional_keys = array_keys($this->OptionalData);
$real_keys = array_diff($data_keys, $optional_keys);
if ($real_keys) {
$ret = '';
foreach ($real_keys as $real_key) {
$ret .= '[' . $real_key . '] = [' . $session_data[$real_key] . ']<br/>';
}
$this->Application->Debugger->appendHTML('Real Keys:<br/> ' . $ret);
}
}
}
if (defined('DEBUG_MODE') && $this->Application->isDebugMode() && kUtil::constOn('DBG_SHOW_PERSISTENTDATA')) {
// dump persistent session data
if ($this->Storage->PersistentVars) {
$this->Application->Debugger->appendHTML('Persistant Session:');
$session_data = $this->Storage->PersistentVars;
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (kUtil::IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
}
}
function SaveData($params = Array ())
{
if (!$this->SetSession()) { // call it here - it may be not set before, because there was no need; if there is a need, it will be set here
return;
}
if (!$this->Application->GetVar('skip_last_template') && $this->Application->GetVar('ajax') != 'yes') {
$this->SaveLastTemplate( $this->Application->GetVar('t'), $params );
}
$this->PrintSession('after save');
$this->Storage->SaveData();
}
/**
* Save last template
*
* @param string $t
* @param Array $params
*/
function SaveLastTemplate($t, $params = Array ())
{
$wid = $this->Application->GetVar('m_wid');
$last_env = $this->getLastTemplateENV($t, Array ('m_opener' => 'u'));
$last_template = basename($_SERVER['PHP_SELF']) . '|' . $last_env;
$this->StoreVar(rtrim('last_template_' . $wid, '_'), $last_template);
// prepare last_template for opener stack, module & session could be added later
$last_env = $this->getLastTemplateENV($t, null, false);
$last_template = basename($_SERVER['PHP_SELF']) . '|' . $last_env;
// save last_template in persistent session
if (!$wid) {
if ($this->Application->isAdmin) {
// only for main window, not popups, not login template, not temp mode (used in adm:MainFrameLink tag)
$temp_mode = false;
$passed = explode(',', $this->Application->GetVar('passed'));
foreach ($passed as $passed_prefix) {
if ($this->Application->GetVar($passed_prefix.'_mode')) {
$temp_mode = true;
break;
}
}
if (!$temp_mode) {
if ( $this->Application->GetVarDirect('section', 'Get') !== false ) {
// check directly in GET, because LinkVar (session -> request) used on these vars
$last_template .= '&section='.$this->Application->GetVar('section').'&module='.$this->Application->GetVar('module');
}
$this->StorePersistentVar('last_template_popup', $last_template);
}
}
elseif ($this->Application->GetVar('admin')) {
// admin checking by session data to prevent recursive session save
static $admin_saved = null;
if (!$this->RecallVar('admin') && !isset($admin_saved)) {
// bug: we get recursion in this place, when cookies are disabled in browser and we are browsing
// front-end in admin's frame (front-end session is initialized using admin's sid and they are
// mixed together)
$admin_saved = true;
$admin_session = $this->Application->recallObject('Session.admin');
/* @var $admin_session Session */
// save to admin last_template too, because when F5 is pressed in frameset Front-End frame should reload as well
$admin_session->StoreVar('last_template_popup', '../' . $last_template);
$admin_session->StorePersistentVar('last_template_popup', '../' . $last_template);
$admin_session->SaveData( Array ('save_last_template' => false) );
}
else {
// don't allow admin=1 & editing_mode=* to get in admin last_template
$last_template = preg_replace('/&(admin|editing_mode)=[\d]/', '', $last_template);
}
}
}
// save other last... variables for mystical purposes (customizations may be)
$this->StoreVar('last_url', $_SERVER['REQUEST_URI']); // needed by ord:StoreContinueShoppingLink
$this->StoreVar('last_env', $last_env);
$save_last_template = array_key_exists('save_last_template', $params) ? $params['save_last_template'] : true;
if ($save_last_template) {
// save last template here, because section & module could be added before
$this->StoreVar(rtrim('last_template_popup_'.$wid, '_'), $last_template);
}
}
function getLastTemplateENV($t, $params = null, $encode = true)
{
if (!isset($params)) {
$params = Array ();
}
$params['__URLENCODE__'] = 1; // uses "&" instead of "&amp;" for url part concatenation + replaces "\" to "%5C" (works in HTML)
if ($this->Application->GetVar('admin') && !array_key_exists('admin', $params) && !defined('EDITING_MODE')) {
$params['editing_mode'] = ''; // used in kApplication::Run
}
$params = array_merge($this->Application->getPassThroughVariables($params), $params);
$ret = $this->Application->BuildEnv($t, $params, 'all', false, false);
if (!$encode) {
// cancels 2nd part of replacements, that URLENCODE does
$ret = str_replace('%5C', '\\', $ret);
}
return $ret;
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
*
* @param string $name Variable name
* @param mixed $value Variable value
* @param bool $optional
* @return void
* @access public
* @see Session::RecallVar()
*/
public function StoreVar($name, $value, $optional = false)
{
$this->Data->Set($name, $value);
if ( $optional ) {
// make variable optional, also remember optional value
$this->OptionalData[$name] = $value;
}
elseif ( !$optional && array_key_exists($name, $this->OptionalData) ) {
if ( $this->OptionalData[$name] == $value ) {
// same value as optional -> don't remove optional mark
return;
}
// make variable non-optional
unset($this->OptionalData[$name]);
}
}
/**
* Stores variable to persistent session
*
* @param string $name
* @param mixed $value
* @param bool $optional
* @return void
* @access public
*/
public function StorePersistentVar($name, $value, $optional = false)
{
$this->Storage->StorePersistentVar($name, $value, $optional);
}
function LoadPersistentVars()
{
$this->Storage->LoadPersistentVars();
}
/**
* Stores default value for session variable
*
* @param string $name
* @param string $value
* @param bool $optional
* @return void
* @access public
* @see Session::RecallVar()
* @see Session::StoreVar()
*/
public function StoreVarDefault($name, $value, $optional = false)
{
$tmp = $this->RecallVar($name);
if ( $tmp === false || $tmp == '' ) {
$this->StoreVar($name, $value, $optional);
}
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @param string $name Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
* @access public
*/
public function RecallVar($name, $default = false)
{
$ret = $this->Data->Get($name);
return ($ret === false) ? $default : $ret;
}
/**
* Returns variable value from persistent session
*
* @param string $name
* @param mixed $default
* @return mixed
* @access public
*/
public function RecallPersistentVar($name, $default = false)
{
return $this->Storage->RecallPersistentVar($name, $default);
}
/**
* Deletes Session variable
*
* @param string $var
* @return void
* @access public
*/
public function RemoveVar($name)
{
$this->Storage->RemoveFromData($name);
$this->Data->Remove($name);
}
/**
* Removes variable from persistent session
*
* @param string $name
* @return void
* @access public
*/
public function RemovePersistentVar($name)
{
$this->Storage->RemovePersistentVar($name);
}
/**
* Ignores session variable value set before
*
* @param string $name
* @return void
* @access public
*/
public function RestoreVar($name)
{
$value = $this->Storage->GetFromData($name, '__missing__');
if ( $value === '__missing__' ) {
// there is nothing to restore (maybe session was not saved), look in optional variable values
$value = array_key_exists($name, $this->OptionalData) ? $this->OptionalData[$name] : false;
}
$this->StoreVar($name, $value);
}
function GetField($var_name, $default = false)
{
return $this->Storage->GetField($var_name, $default);
}
function SetField($var_name, $value)
{
$this->Storage->SetField($var_name, $value);
}
/**
* Deletes expired sessions
*
* @return Array expired sids if any
* @access private
*/
function DeleteExpired()
{
return $this->Storage->DeleteExpired();
}
/**
* Deletes given sessions
*
* @param $session_ids
* @param int $delete_reason
* @return void
*/
function DeleteSessions($session_ids, $delete_reason = SESSION_LOG_EXPIRED)
{
$this->Storage->DeleteSessions($session_ids, $delete_reason);
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
$user_id = $this->RecallVar('user_id');
$ret = $user_id > 0;
if (($this->RecallVar('admin') == 1 || defined('ADMIN')) && ($user_id == USER_ROOT)) {
$ret = true;
}
return $ret;
}
}
\ No newline at end of file
Index: branches/5.2.x/core/kernel/globals.php
===================================================================
--- branches/5.2.x/core/kernel/globals.php (revision 15516)
+++ branches/5.2.x/core/kernel/globals.php (revision 15517)
@@ -1,860 +1,885 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kUtil {
// const KG_TO_POUND = 2.20462262;
const POUND_TO_KG = 0.45359237;
/**
* Similar to array_merge_recursive but keyed-valued are always overwritten.
* Priority goes to the 2nd array.
*
* @param $paArray1 array
* @param $paArray2 array
* @return array
* @access public
*/
public static function array_merge_recursive($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2)) {
return $paArray2;
}
foreach ($paArray2 AS $sKey2 => $sValue2) {
$paArray1[$sKey2] = isset($paArray1[$sKey2]) ? self::array_merge_recursive($paArray1[$sKey2], $sValue2) : $sValue2;
}
return $paArray1;
}
/**
* Prepend a reference to an element to the beginning of an array.
* Renumbers numeric keys, so $value is always inserted to $array[0]
*
* @param $array array
* @param $value mixed
* @return int
* @access public
*/
public static function array_unshift_ref(&$array, &$value)
{
$return = array_unshift($array,'');
$array[0] =& $value;
return $return;
}
/**
* Rename key in associative array, maintaining keys order
*
* @param Array $array Associative Array
* @param mixed $old Old key name
* @param mixed $new New key name
* @access public
*/
public static function array_rename_key(&$array, $old, $new)
{
$new_array = Array ();
foreach ($array as $key => $val) {
$new_array[ $key == $old ? $new : $key] = $val;
}
$array = $new_array;
}
/**
* Same as print_r, but outputs result on screen or in debugger report (when in debug mode)
*
* @param Array $data
* @param string $label
* @param bool $on_screen
* @access public
*/
public static function print_r($data, $label = '', $on_screen = false)
{
$is_debug = false;
if ( class_exists('kApplication') && !$on_screen ) {
$application =& kApplication::Instance();
$is_debug = $application->isDebugMode();
}
if ( $is_debug && isset($application) ) {
if ( $label ) {
$application->Debugger->appendHTML('<strong>' . $label . '</strong>');
}
$application->Debugger->dumpVars($data);
}
else {
if ( $label ) {
echo '<strong>' . $label . '</strong><br/>';
}
echo '<pre>', print_r($data, true), '</pre>';
}
}
/**
* Define constant if it was not already defined before
*
* @param string $const_name
* @param string $const_value
* @access public
*/
public static function safeDefine($const_name, $const_value)
{
if ( !defined($const_name) ) {
define($const_name, $const_value);
}
}
/**
* Parses "/system/config.php" file and returns the result
*
* @param bool $parse_section
* @return Array
* @access public
*/
public static function parseConfig($parse_section = false)
{
$file = FULL_PATH . DIRECTORY_SEPARATOR . 'system' . DIRECTORY_SEPARATOR . 'config.php';
if ( !file_exists($file) ) {
return Array ();
}
if ( file_exists($file) && !is_readable($file) ) {
die('Could Not Open Ini File');
}
$contents = file($file);
if ( $contents && $contents[0] == '<' . '?' . 'php die() ?' . ">\n" ) {
// format of "config.php" file before 5.1.0 version
array_shift($contents);
return parse_ini_string(implode('', $contents), $parse_section);
}
$_CONFIG = Array ();
require($file);
if ( $parse_section ) {
if ( isset($_CONFIG['Database']['LoadBalancing']) && $_CONFIG['Database']['LoadBalancing'] ) {
require FULL_PATH . DIRECTORY_SEPARATOR . 'system' . DIRECTORY_SEPARATOR . 'db_servers.php';
}
return $_CONFIG;
}
$ret = Array ();
foreach ($_CONFIG as $section => $section_variables) {
$ret = array_merge($ret, $section_variables);
}
return $ret;
}
/**
* Returns parsed variables from "config.php" file
*
* @return Array
* @access public
*/
public static function getConfigVars()
{
static $vars = NULL;
if ( !isset($vars) ) {
$vars = self::parseConfig();
}
return $vars;
}
/**
* Same as "include_once", but also profiles file includes in debug mode and DBG_PROFILE_INCLUDES constant is set
*
* @param string $file
* @access public
*/
public static function includeOnce($file)
{
global $debugger;
if ( defined('DEBUG_MODE') && DEBUG_MODE && isset($debugger) && defined('DBG_PROFILE_INCLUDES') && DBG_PROFILE_INCLUDES ) {
if ( in_array($file, get_included_files()) ) {
return ;
}
global $debugger;
/*$debugger->IncludeLevel++;
$before_mem = memory_get_usage();*/
$debugger->ProfileStart('inc_'.crc32($file), $file);
include_once($file);
$debugger->ProfileFinish('inc_'.crc32($file));
$debugger->profilerAddTotal('includes', 'inc_'.crc32($file));
/*$used_mem = memory_get_usage() - $before_mem;
$debugger->IncludeLevel--;
$debugger->IncludesData['file'][] = str_replace(FULL_PATH, '', $file);
$debugger->IncludesData['mem'][] = $used_mem;
$debugger->IncludesData['time'][] = $used_time;
$debugger->IncludesData['level'][] = $debugger->IncludeLevel;*/
}
else {
include_once($file);
}
}
/**
* Checks if given string is a serialized array
*
* @param string $string
* @return bool
* @access public
*/
public static function IsSerialized($string)
{
if ( is_array($string) ) {
return false;
}
return preg_match('/a:([\d]+):{/', $string);
}
/**
* Generates password of given length
*
* @param int $length
* @return string
* @access public
*/
public static function generatePassword($length = 10)
{
$pass_length = $length;
$p1 = Array ('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2 = Array ('a','e','i','o','u');
$p3 = Array ('1','2','3','4','5','6','7','8','9');
$p4 = Array ('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1 = 21;// this is the count of $p1
$s2 = 5; // this is the count of $p2
$s3 = 9; // this is the count of $p3
$s4 = 5; // this is the count of $p4
// possible readable combinations
$c1 = '121'; // will be like 'bab'
$c2 = '212'; // will be like 'aba'
$c3 = '12'; // will be like 'ab'
$c4 = '3'; // will be just a number '1 to 9' if you dont like number delete the 3
//$c5 = '4'; // uncomment to active the strong stuff
$comb = '4'; // the amount of combinations you made above (and did not comment out)
for ($p = 0; $p < $pass_length;) {
mt_srand((double)microtime() * 1000000);
$strpart = mt_rand(1, $comb);
// checking if the stringpart is not the same as the previous one
if ($strpart != $previous) {
$pass_structure .= ${'c' . $strpart};
// shortcutting the loop a bit
$p = $p + mb_strlen(${'c' . $strpart});
}
$previous = $strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g = 0; $g < mb_strlen($pass_structure); $g++) {
mt_srand((double)microtime() * 1000000);
$sel = mb_substr($pass_structure, $g, 1);
$pass .= ${'p' . $sel}[ mt_rand(0,-1+${'s'.$sel}) ];
}
return $pass;
}
/**
* submits $url with $post as POST
*
* @param string $url
* @param mixed $data
* @param Array $headers
* @param string $request_type
* @param Array $curl_options
* @return string
* @access public
* @deprecated
*/
public static function curl_post($url, $data, $headers = NULL, $request_type = 'POST', $curl_options = NULL)
{
$application =& kApplication::Instance();
$curl_helper = $application->recallObject('CurlHelper');
/* @var $curl_helper kCurlHelper */
if ($request_type == 'POST') {
$curl_helper->SetRequestMethod(kCurlHelper::REQUEST_METHOD_POST);
}
$curl_helper->SetRequestData($data);
if (!is_null($headers)) {
// not an associative array, so don't use kCurlHelper::SetHeaders method
$curl_helper->setOptions( Array (CURLOPT_HTTPHEADER => $headers) );
}
if (is_array($curl_options)) {
$curl_helper->setOptions($curl_options);
}
$curl_helper->followLocation = false;
$ret = $curl_helper->Send($url);
$GLOBALS['curl_errorno'] = $curl_helper->lastErrorCode;
$GLOBALS['curl_error'] = $curl_helper->lastErrorMsg;
return $ret;
}
/**
* Checks if constant is defined and has positive value
*
* @param string $const_name
* @return bool
* @access public
*/
public static function constOn($const_name)
{
return defined($const_name) && constant($const_name);
}
/**
* Converts KG to Pounds
*
* @param float $kg
* @param bool $pounds_only
* @return float
* @access public
*/
public static function Kg2Pounds($kg, $pounds_only = false)
{
$major = floor( round($kg / self::POUND_TO_KG, 3) );
$minor = abs(round(($kg - $major * self::POUND_TO_KG) / self::POUND_TO_KG * 16, 2));
if ($pounds_only) {
$major += round($minor * 0.0625, 2);
$minor = 0;
}
return array($major, $minor);
}
/**
* Converts Pounds to KG
*
* @param float $pounds
* @param float $ounces
* @return float
* @access public
*/
public static function Pounds2Kg($pounds, $ounces = 0.00)
{
return round(($pounds + ($ounces / 16)) * self::POUND_TO_KG, 5);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
public static function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
/**
* Enter description here...
*
* @param resource $filePointer the file resource to write to
* @param Array $data the data to write out
* @param string $delimiter the field separator
* @param string $enclosure symbol to enclose field data to
* @param string $recordSeparator symbols to separate records with
* @access public
*/
public static function fputcsv($filePointer, $data, $delimiter = ',', $enclosure = '"', $recordSeparator = "\r\n")
{
fwrite($filePointer, self::getcsvline($data, $delimiter, $enclosure, $recordSeparator));
}
/**
* Enter description here...
*
* @param Array $data the data to write out
* @param string $delimiter the field separator
* @param string $enclosure symbol to enclose field data to
* @param string $recordSeparator symbols to separate records with
* @return string
* @access public
*/
public static function getcsvline($data, $delimiter = ',', $enclosure = '"', $recordSeparator = "\r\n")
{
foreach($data as $field_index => $field_value) {
// replaces an enclosure with two enclosures
$data[$field_index] = str_replace($enclosure, $enclosure.$enclosure, $field_value);
}
$line = $enclosure.implode($enclosure.$delimiter.$enclosure, $data).$enclosure.$recordSeparator;
$line = preg_replace('/'.preg_quote($enclosure, '/').'([0-9\.]+)'.preg_quote($enclosure, '/').'/', '$1', $line);
return $line;
}
/**
* Allows to replace #section# within any string with current section
*
* @param string $string
* @return string
* @access public
*/
public static function replaceModuleSection($string)
{
$application =& kApplication::Instance();
$module_section = $application->RecallVar('section');
if ($module_section) {
// substitute section instead of #section# parameter in title preset name
$module_section = explode(':', $module_section);
$section = preg_replace('/(configuration|configure)_(.*)/i', '\\2', $module_section[count($module_section) == 2 ? 1 : 0]);
$string = str_replace('#section#', mb_strtolower($section), $string);
}
return $string;
}
/**
* Checks, that user IP address is within allowed range
*
* @param string $ip_list semi-column (by default) separated ip address list
* @param string $separator ip address separator (default ";")
*
* @return bool
* @access public
*/
public static function ipMatch($ip_list, $separator = ';')
{
if ( !isset($_SERVER['REMOTE_ADDR']) ) {
// PHP CLI used -> never match
return false;
}
$ip_match = false;
$ip_addresses = $ip_list ? explode($separator, $ip_list) : Array ();
foreach ($ip_addresses as $ip_address) {
if (self::netMatch($ip_address, $_SERVER['REMOTE_ADDR'])) {
$ip_match = true;
break;
}
}
return $ip_match;
}
/**
* Checks, that given ip belongs to given subnet
*
* @param string $network
* @param string $ip
* @return bool
* @access public
*/
public static function netMatch($network, $ip)
{
$network = trim($network);
$ip = trim($ip);
if ( preg_replace('/[\d\.\/-]/', '', $network) != '' ) {
$network = gethostbyname($network);
}
if ($network == $ip) {
// comparing two ip addresses directly
return true;
}
$d = strpos($network, '-');
if ($d !== false) {
// ip address range specified
$from = ip2long(trim(substr($network, 0, $d)));
$to = ip2long(trim(substr($network, $d + 1)));
$ip = ip2long($ip);
return ($ip >= $from && $ip <= $to);
}
elseif (strpos($network, '/') !== false) {
// single subnet specified
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)) {
$ip_arr[0] .= '.0'; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
return false;
}
/**
* Returns mime type corresponding to given file
* @param string $file
* @return string
* @access public
*/
public static function mimeContentType($file)
{
$ret = '';
if ( function_exists('finfo_open') && function_exists('finfo_file') ) {
$mime_magic_resource = finfo_open(FILEINFO_MIME_TYPE);
if ( $mime_magic_resource ) {
$ret = finfo_file($mime_magic_resource, $file);
finfo_close($mime_magic_resource);
}
}
elseif ( function_exists('mime_content_type') ) {
$ret = mime_content_type($file);
}
return $ret ? $ret : self::mimeContentTypeByExtension($file);
}
/**
* Detects mime type of the file purely based on it's extension
*
* @param string $file
* @return string
* @access public
*/
public static function mimeContentTypeByExtension($file)
{
$file_extension = mb_strtolower( pathinfo($file, PATHINFO_EXTENSION) );
$mapping = '(xls:application/excel)(hqx:application/macbinhex40)(doc,dot,wrd:application/msword)(pdf:application/pdf)
(pgp:application/pgp)(ps,eps,ai:application/postscript)(ppt:application/powerpoint)(rtf:application/rtf)
(tgz,gtar:application/x-gtar)(gz:application/x-gzip)(php,php3:application/x-httpd-php)(js:application/x-javascript)
(ppd,psd:application/x-photoshop)(swf,swc,rf:application/x-shockwave-flash)(tar:application/x-tar)(zip:application/zip)
(mid,midi,kar:audio/midi)(mp2,mp3,mpga:audio/mpeg)(ra:audio/x-realaudio)(wav:audio/wav)(bmp:image/bitmap)(bmp:image/bitmap)
(gif:image/gif)(iff:image/iff)(jb2:image/jb2)(jpg,jpe,jpeg:image/jpeg)(jpx:image/jpx)(png:image/png)(tif,tiff:image/tiff)
(wbmp:image/vnd.wap.wbmp)(xbm:image/xbm)(css:text/css)(txt:text/plain)(htm,html:text/html)(xml:text/xml)
(mpg,mpe,mpeg:video/mpeg)(qt,mov:video/quicktime)(avi:video/x-ms-video)(eml:message/rfc822)
(sxw:application/vnd.sun.xml.writer)(sxc:application/vnd.sun.xml.calc)(sxi:application/vnd.sun.xml.impress)
(sxd:application/vnd.sun.xml.draw)(sxm:application/vnd.sun.xml.math)
(odt:application/vnd.oasis.opendocument.text)(oth:application/vnd.oasis.opendocument.text-web)
(odm:application/vnd.oasis.opendocument.text-master)(odg:application/vnd.oasis.opendocument.graphics)
(odp:application/vnd.oasis.opendocument.presentation)(ods:application/vnd.oasis.opendocument.spreadsheet)
(odc:application/vnd.oasis.opendocument.chart)(odf:application/vnd.oasis.opendocument.formula)
(odi:application/vnd.oasis.opendocument.image)';
if ( preg_match('/[\(,]' . $file_extension . '[,]{0,1}.*?:(.*?)\)/s', $mapping, $regs) ) {
return $regs[1];
}
return 'application/octet-stream';
}
/**
* Return param value and removes it from params array
*
* @param string $name
* @param Array $params
* @param bool $default
* @return string
*/
public static function popParam($name, &$params, $default = false)
{
if ( isset($params[$name]) ) {
$value = $params[$name];
unset($params[$name]);
return $value;
}
return $default;
}
/**
* Generate subpath from hashed value
*
* @param string $name
* @param int $levels
* @return string
*/
public static function getHashPathForLevel($name, $levels = 2)
{
if ( $levels == 0 ) {
return '';
}
else {
$path = '';
$hash = md5($name);
for ($i = 0; $i < $levels; $i++) {
$path .= substr($hash, $i, 1) . '/';
}
return $path;
}
}
/**
* Calculates the crc32 polynomial of a string (always positive number)
*
* @param string $str
* @return int
*/
public static function crc32($str)
{
return sprintf('%u', crc32($str));
}
/**
* Returns instance of DateTime class with date set based on timestamp
*
* @static
* @param int $timestamp
* @return DateTime
* @access public
*/
public static function dateFromTimestamp($timestamp)
{
if ( version_compare(PHP_VERSION, '5.3.0', '<') ) {
$date = new DateTime('@' . $timestamp);
$date->setTimezone(new DateTimeZone(getenv('TZ')));
}
else {
$date = new DateTime();
$date->setTimestamp($timestamp);
}
return $date;
}
/**
* Returns timestamp from given DateTime class instance
*
* @static
* @param DateTime $date_time
* @return int|string
* @access public
*/
public static function timestampFromDate(DateTime $date_time)
{
if ( version_compare(PHP_VERSION, '5.3.0', '<') ) {
return $date_time->format('U');
}
return $date_time->getTimestamp();
}
+
+ /**
+ * Generates random numeric id
+ *
+ * @static
+ * @return string
+ * @access public
+ */
+ public static function generateId()
+ {
+ list($usec, $sec) = explode(' ', microtime());
+
+ $id_part_1 = substr($usec, 4, 4);
+ $id_part_2 = mt_rand(1, 9);
+ $id_part_3 = substr($sec, 6, 4);
+ $digit_one = substr($id_part_1, 0, 1);
+
+ if ( $digit_one == 0 ) {
+ $digit_one = mt_rand(1, 9);
+ $id_part_1 = preg_replace('/^0/', '', $id_part_1);
+ $id_part_1 = $digit_one . $id_part_1;
+ }
+
+ return $id_part_1 . $id_part_2 . $id_part_3;
+ }
}
/**
* Returns array value if key exists
* Accepts infinite number of parameters
*
* @param Array $array searchable array
* @param int $key array key
* @return string
*/
function getArrayValue(&$array, $key)
{
$ret = isset($array[$key]) ? $array[$key] : false;
if ( $ret && func_num_args() > 2 ) {
for ($i = 2; $i < func_num_args(); $i++) {
$cur_key = func_get_arg($i);
$ret = getArrayValue($ret, $cur_key);
if ( $ret === false ) {
break;
}
}
}
return $ret;
}
if ( !function_exists('parse_ini_string') ) {
/**
* Equivalent for "parse_ini_string" function available since PHP 5.3.0
*
* @param string $ini
* @param bool $process_sections
* @param int $scanner_mode
* @return Array
*/
function parse_ini_string($ini, $process_sections = false, $scanner_mode = NULL)
{
# Generate a temporary file.
$tempname = tempnam('/tmp', 'ini');
$fp = fopen($tempname, 'w');
fwrite($fp, $ini);
$ini = parse_ini_file($tempname, !empty($process_sections));
fclose($fp);
@unlink($tempname);
return $ini;
}
}
if ( !function_exists('memory_get_usage') ) {
// PHP 4.x and compiled without --enable-memory-limit option
function memory_get_usage() { return -1; }
}
if ( !function_exists('imagecreatefrombmp') ) {
// just in case if GD will add this function in future
function imagecreatefrombmp($filename)
{
//Ouverture du fichier en mode binaire
if (! $f1 = fopen($filename,"rb")) return FALSE;
//1 : Chargement des ent�tes FICHIER
$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
if ($FILE['file_type'] != 19778) return FALSE;
//2 : Chargement des ent�tes BMP
$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
$BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
$BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal'] = 4-(4*$BMP['decal']);
if ($BMP['decal'] == 4) $BMP['decal'] = 0;
//3 : Chargement des couleurs de la palette
$PALETTE = array();
if ($BMP['colors'] < 16777216)
{
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
}
//4 : Cr�ation de l'image
$IMG = fread($f1,$BMP['size_bitmap']);
$VIDE = chr(0);
$res = imagecreatetruecolor($BMP['width'],$BMP['height']);
$P = 0;
$Y = $BMP['height']-1;
while ($Y >= 0)
{
$X=0;
while ($X < $BMP['width'])
{
if ($BMP['bits_per_pixel'] == 24)
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
elseif ($BMP['bits_per_pixel'] == 16)
{
$COLOR = unpack("n",substr($IMG,$P,2));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 8)
{
$COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 4)
{
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 1)
{
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7;
elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
else
return FALSE;
imagesetpixel($res,$X,$Y,$COLOR[1]);
$X++;
$P += $BMP['bytes_per_pixel'];
}
$Y--;
$P+=$BMP['decal'];
}
//Fermeture du fichier
fclose($f1);
return $res;
}
}
\ No newline at end of file
Index: branches/5.2.x/core/units/users/users_tag_processor.php
===================================================================
--- branches/5.2.x/core/units/users/users_tag_processor.php (revision 15516)
+++ branches/5.2.x/core/units/users/users_tag_processor.php (revision 15517)
@@ -1,380 +1,362 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class UsersTagProcessor extends kDBTagProcessor
{
function LogoutLink($params)
{
$pass = Array('pass' => 'all,m,u', 'u_event' => 'OnLogout', 'm_cat_id' => 0);
$logout_template = $this->SelectParam($params, 'template,t');
return $this->Application->HREF($logout_template, '', $pass);
}
function RegistrationEnabled($params)
{
return $this->Application->ConfigValue('User_Allow_New') != 2;
}
function SuggestRegister($params)
{
return !$this->Application->LoggedIn() && !$this->Application->ConfigValue('Comm_RequireLoginBeforeCheckout') && $this->RegistrationEnabled($params);
}
function ConfirmPasswordLink($params)
{
$user = $this->Application->recallObject($this->Prefix . '.email-to');
/* @var $user UsersItem */
$code = $this->getCachedCode();
$user->SetDBField('PwResetConfirm', $code);
$user->SetDBField('PwRequestTime_date', adodb_mktime());
$user->SetDBField('PwRequestTime_time', adodb_mktime());
if ( $user->GetChangedFields() ) {
// tag is called 2 times within USER.PWDC email event, so don't update user record twice
$user->Update();
}
$params['user_key'] = $code;
if ( !$this->SelectParam($params, 'template,t') ) {
$params['template'] = $this->Application->GetVar('reset_confirm_template');
}
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
/**
* Generates & caches code for password confirmation link
*
* @return string
*/
function getCachedCode()
{
static $code = null;
if ( !isset($code) ) {
- $code = md5($this->GenerateCode());
+ $code = md5(kUtil::generateId());
}
return $code;
}
- function GenerateCode()
- {
- list($usec, $sec) = explode(" ",microtime());
-
- $id_part_1 = substr($usec, 4, 4);
- $id_part_2 = mt_rand(1,9);
- $id_part_3 = substr($sec, 6, 4);
- $digit_one = substr($id_part_1, 0, 1);
-
- if ($digit_one == 0) {
- $digit_one = mt_rand(1,9);
- $id_part_1 = preg_replace('/^0/', '', $id_part_1);
- $id_part_1=$digit_one.$id_part_1;
- }
-
- return $id_part_1.$id_part_2.$id_part_3;
- }
-
function TestCodeIsValid($params)
{
$user_helper = $this->Application->recallObject('UserHelper');
/* @var $user_helper UserHelper */
$code_type = isset($params['code_type']) ? $params['code_type'] : 'forgot_password';
$expiration_timeout = isset($params['expiration_timeout']) ? $params['expiration_timeout'] : null;
$user_id = $user_helper->validateUserCode($this->Application->GetVar('user_key'), $code_type, $expiration_timeout);
if ( !is_numeric($user_id) ) {
// used for error reporting only -> rewrite code + theme (by Alex)
$object = $this->getObject( Array('skip_autoload' => true) ); // TODO: change theme too
/* @var $object UsersItem */
$object->SetError('PwResetConfirm', $user_id, $this->_getUserCodeErrorMsg($user_id, $code_type, $params));
return false;
}
return true;
}
/**
* Tries to restore user email
*
* @param Array $params
* @return bool
* @access protected
*/
protected function RestoreEmail($params)
{
$user_helper = $this->Application->recallObject('UserHelper');
/* @var $user_helper UserHelper */
$hash = $this->Application->GetVar('hash');
$error_code = $user_helper->restoreEmail($hash);
if ( $error_code ) {
// used for error reporting only -> rewrite code + theme (by Alex)
$object = $this->getObject(Array ('skip_autoload' => true)); // TODO: change theme too
/* @var $object UsersItem */
$object->SetError('PwResetConfirm', 'restore', $params[$error_code]);
return false;
}
return true;
}
/**
* Returns error message set by given code type
*
* @param string $error_code
* @param string $code_type
* @param Array $params
* @return string
*/
function _getUserCodeErrorMsg($error_code, $code_type, $params)
{
$error_messages = Array (
'forgot_password' => Array (
'code_is_not_valid' => 'lu_code_is_not_valid',
'code_expired' => 'lu_code_expired',
),
'activation' => Array (
'code_is_not_valid' => 'lu_error_ActivationCodeNotValid',
'code_expired' => 'lu_error_ActivationCodeExpired',
),
'verify_email' => Array (
'code_is_not_valid' => 'lu_error_VerificationCodeNotValid',
'code_expired' => 'lu_error_VerificationCodeExpired',
),
);
if ($code_type == 'custom') {
// custom error messages are given directly in tag
$error_messages[$code_type] = Array (
'code_is_not_valid' => $params['error_invalid'],
'code_expired' => $params['error_expired'],
);
}
return $error_messages[$code_type][$error_code];
}
/**
* Returns site administrator email
*
* @param Array $params
* @return string
*/
function SiteAdminEmail($params)
{
return $this->Application->ConfigValue('DefaultEmailSender');
}
/**
* Returns login name of user
*
* @param Array $params
* @return string
* @access protected
*/
protected function LoginName($params)
{
$object = $this->getObject($params);
/* @var $object UsersItem */
return $object->GetID() != USER_ROOT ? $object->GetDBField('Username') : 'root';
}
function CookieUsername($params)
{
$items_info = $this->Application->GetVar( $this->getPrefixSpecial(true) );
if ( $items_info !== false ) {
return $items_info[USER_GUEST][ $params['field'] ];
}
$username = $this->Application->GetVar('save_username'); // from cookie
if ($username == 'super-root') {
$username = 'root';
}
return $username === false ? '' : $username;
}
/**
* Checks if user have one of required permissions
*
* @param Array $params
* @return bool
*/
function HasPermission($params)
{
$perm_helper = $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
return $perm_helper->TagPermissionCheck($params);
}
/**
* Returns link to user public profile
*
* @param Array $params
* @return string
*/
function ProfileLink($params)
{
$object = $this->getObject($params);
$params['user_id'] = $object->GetID();
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
function ImageSrc($params)
{
list ($ret, $tag_processed) = $this->processAggregatedTag('ImageSrc', $params, $this->getPrefixSpecial());
return $tag_processed ? $ret : false;
}
function LoggedIn($params)
{
static $loggedin_status = Array ();
$object = $this->getObject($params);
/* @var $object kDBList */
if (!isset($loggedin_status[$this->Special])) {
$user_ids = $object->GetCol($object->IDField);
$sql = 'SELECT LastAccessed, '.$object->IDField.'
FROM '.TABLE_PREFIX.'UserSessions
WHERE (PortalUserId IN ('.implode(',', $user_ids).'))';
$loggedin_status[$this->Special] = $this->Conn->GetCol($sql, $object->IDField);
}
return isset($loggedin_status[$this->Special][$object->GetID()]);
}
/**
* Prints user activation link
*
* @param Array $params
* @return string
*/
function ActivationLink($params)
{
$object = $this->getObject($params);
/* @var $object kDBItem */
$code = $this->getCachedCode();
$object->SetDBField('PwResetConfirm', $code);
$object->SetDBField('PwRequestTime_date', adodb_mktime());
$object->SetDBField('PwRequestTime_time', adodb_mktime());
$object->Update();
$params['user_key'] = $code;
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
/**
* Returns link to revert e-mail change in user record
*
* @param Array $params
* @return string
* @access protected
*/
protected function UndoEmailChangeLink($params)
{
$params['hash'] = $this->Application->Parser->GetParam('hash');
if ( !$this->SelectParam($params, 'template,t') ) {
$params['template'] = $this->Application->GetVar('undo_email_template');
}
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
/**
* Activates user using given code
*
* @param Array $params
* @return string
* @access protected
*/
protected function ActivateUser($params)
{
$this->_updateAndLogin(Array ('Status' => STATUS_ACTIVE, 'EmailVerified' => 1));
return '';
}
/**
* Marks user e-mail as verified using given code
*
* @param Array $params
* @return string
* @access protected
*/
protected function MarkUserEmailAsVerified($params)
{
$this->_updateAndLogin(Array ('EmailVerified' => 1));
return '';
}
/**
* Activates user using given code
*
* @param Array $fields_hash
* @return void
* @access protected
*/
protected function _updateAndLogin($fields_hash)
{
$user_helper = $this->Application->recallObject('UserHelper');
/* @var $user_helper UserHelper */
$user = $this->Application->recallObject($this->Prefix . '.activate', null, Array ('skip_autoload' => true));
/* @var $user UsersItem */
$user->Load(trim($this->Application->GetVar('user_key')), 'PwResetConfirm');
if ( !$user->isLoaded() ) {
return ;
}
$user->SetFieldsFromHash($fields_hash);
$user->SetDBField('PwResetConfirm', '');
$user->SetDBField('PwRequestTime_date', NULL);
$user->SetDBField('PwRequestTime_time', NULL);
$user->Update();
$login_user =& $user_helper->getUserObject();
$login_user->Load( $user->GetID() );
if ( ($login_user->GetDBField('Status') == STATUS_ACTIVE) && $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $login_user->GetID() );
}
}
}
\ No newline at end of file

Event Timeline