Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Fri, Feb 21, 11:59 PM

in-portal

Index: branches/5.2.x/core/kernel/utility/http_query.php
===================================================================
--- branches/5.2.x/core/kernel/utility/http_query.php (revision 16803)
+++ branches/5.2.x/core/kernel/utility/http_query.php (revision 16804)
@@ -1,823 +1,827 @@
<?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 kHTTPQuery extends Params {
/**
* Cache of QueryString parameters
* from config, that are represented
* in environment variable
*
* @var Array
*/
protected $discoveredUnits = Array ();
/**
* $_POST vars
*
* @var Array
* @access private
*/
var $Post;
/**
* $_GET vars
*
* @var Array
* @access private
*/
var $Get;
/**
* $_COOKIE vars
*
* @var Array
* @access private
*/
var $Cookie = array();
/**
* $_SERVER vars
*
* @var Array
* @access private
*/
var $Server;
/**
* $_ENV vars
*
* @var Array
* @access private
*/
var $Env;
/**
* Order in what write
* all vars together in
* the same array
*
* @var string
*/
var $Order;
/**
* Uploaded files info
*
* @var Array
* @access private
*/
var $Files;
var $specialsToRemove = Array();
/**
* SessionID is given via "sid" variable in query string
*
* @var bool
*/
var $_sidInQueryString = false;
/**
* Trust information, provided by proxy
*
* @var bool
*/
protected $_trustProxy = false;
/**
* Loads info from $_POST, $_GET and related arrays into common place.
*
* @param string $order Order.
*
* @throws RuntimeException When "Proxy" header is present in Web Request.
*/
- public function __construct($order = 'CGPF')
+ public function __construct($order = 'GPF')
{
parent::__construct();
// Don't process cookies from CLI.
if ( PHP_SAPI === 'cli' ) {
$order = str_replace('C', '', $order);
}
$this->Order = $order;
if ( isset($_SERVER['HTTP_PROXY']) && PHP_SAPI !== 'cli' ) {
throw new RuntimeException('Web Requests with "Proxy" header are forbidden.');
}
if ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) {
// When AJAX request is made from jQuery, then create ajax variable,
// so any logic based in it (like redirects) will not break down.
$_GET['ajax'] = 'yes';
}
$this->_trustProxy = kUtil::getSystemConfig()->get('TrustProxy');
}
/**
* Discovers unit form request and returns it's QueryString option on success
*
* @param string $prefix_special
*
* @return Array|bool
* @access public
*/
public function discoverUnit($prefix_special)
{
list($prefix) = explode('.', $prefix_special);
$query_string = $this->getQueryString($prefix);
if ($query_string) {
// only units with QueryString option can be discovered
$this->discoveredUnits[$prefix_special] = $query_string;
return $query_string;
}
unset( $this->discoveredUnits[$prefix] );
return false;
}
/**
* Returns units, passed in request
*
* @param bool $prefix_special_only
* @return Array
* @access protected
*/
public function getDiscoveredUnits($prefix_special_only = true)
{
return $prefix_special_only ? array_keys( $this->discoveredUnits ) : $this->discoveredUnits;
}
/**
* Returns QueryMap for requested unit config.
* In case if unit config is a clone, then get parent item's (from prefix) config to create clone
*
* @param string $prefix
* @return Array
* @access protected
*/
protected function getQueryString($prefix)
{
$ret = $this->Application->getUnitOption($prefix, 'QueryString', Array ());
if ( !$ret && preg_match('/(.*?)-(.*)/', $prefix, $regs) ) {
// "#prefix" (new format), "prefix" (old format)
return $this->_getQueryString('#' . $regs[2]);
}
return $ret;
}
/**
* Returns query string (with safety check against missing prefixes)
*
* @param string $prefix
* @return Array
*/
private function _getQueryString($prefix)
{
if ( $this->Application->prefixRegistred($prefix) ) {
return $this->Application->getUnitOption($prefix, 'QueryString');
}
return substr($prefix, 0, 1) == '#' ? $this->_getQueryString( substr($prefix, 1) ) : Array ();
}
/**
* Removes specials from request
*
* @param Array $array
* @return Array
* @access protected
*/
protected function _removeSpecials($array)
{
$ret = Array ();
$removed = false;
foreach ($this->specialsToRemove as $prefix_special => $flag) {
if ( $flag ) {
$removed = true;
list ($prefix, $special) = explode('.', $prefix_special, 2);
foreach ($array as $key => $val) {
$new_key = preg_match("/^" . $prefix . "[._]{1}" . $special . "(.*)/", $key, $regs) ? $prefix . $regs[1] : $key;
$ret[$new_key] = is_array($val) ? $this->_removeSpecials($val) : $val;
}
}
}
return $removed ? $ret : $array;
}
public function process()
{
$this->AddAllVars();
$this->removeSpecials();
ini_set('magic_quotes_gpc', 0);
$this->Application->UrlManager->LoadStructureTemplateMapping();
$this->AfterInit();
}
/**
* All all requested vars to
* common storage place
*
* @return void
* @access protected
*/
protected function AddAllVars()
{
for ($i = 0; $i < strlen($this->Order); $i++) {
switch ($this->Order[$i]) {
case 'G':
$this->Get = $this->AddVars($_GET);
if ( array_key_exists('sid', $_GET) ) {
$this->_sidInQueryString = true;
}
$vars = $this->Application->processQueryString($this->Get(ENV_VAR_NAME));
if ( array_key_exists('sid', $vars) ) {
// used by Session::GetPassedSIDValue
$this->Get['sid'] = $vars['sid'];
}
$this->AddParams($vars);
break;
case 'P':
$this->Post = $this->AddVars($_POST);
$this->convertPostEvents();
$this->_processPostEnvVariables();
break;
case 'C':
$this->Cookie = $this->AddVars($_COOKIE);
break;
/*case 'E';
$this->Env = $this->AddVars($_ENV, false); //do not strip slashes!
break;
case 'S';
$this->Server = $this->AddVars($_SERVER, false); //do not strip slashes!
break;*/
case 'F';
$this->convertFiles();
$this->Files = $this->MergeVars($_FILES); // , false); //do not strip slashes!
break;
}
}
+
+ if ( strpos($this->Order, 'C') === false ) {
+ $this->Cookie = $this->StripSlashes($_COOKIE);
+ }
}
/**
* Allow POST variables, that names were transformed by PHP ("." replaced with "_") to
* override variables, that were virtually created through environment variable parsing
*
*/
function _processPostEnvVariables()
{
$passed = $this->Get('passed');
if ( !$passed ) {
return;
}
$passed = explode(',', $passed);
foreach ($passed as $prefix_special) {
if ( strpos($prefix_special, '.') === false ) {
continue;
}
list ($prefix, $special) = explode('.', $prefix_special);
$query_map = $this->getQueryString($prefix);
$post_prefix_special = $prefix . '_' . $special;
foreach ($query_map as $var_name) {
if ( array_key_exists($post_prefix_special . '_' . $var_name, $this->Post) ) {
$this->Set($prefix_special . '_' . $var_name, $this->Post[$post_prefix_special . '_' . $var_name]);
}
}
}
}
/**
* Removes requested specials from all request variables
*
* @return void
* @access protected
*/
protected function removeSpecials()
{
$this->specialsToRemove = $this->Get('remove_specials');
if ( $this->specialsToRemove ) {
foreach ($this->specialsToRemove as $prefix_special => $flag) {
if ( $flag && strpos($prefix_special, '.') === false ) {
unset($this->specialsToRemove[$prefix_special]);
trigger_error('Incorrect usage of "<strong>remove_specials[' . $prefix_special . ']</strong>" field (no special found)', E_USER_NOTICE);
}
}
$this->_Params = $this->_removeSpecials($this->_Params);
}
}
/**
* Finishes initialization of kHTTPQuery class
*
* @return void
* @access protected
* @todo: only uses build-in rewrite listeners, when cache is build for the first time
*/
protected function AfterInit()
{
$rewrite_url = $this->Get('_mod_rw_url_');
if ( !is_string($rewrite_url) ) {
$rewrite_url = '';
}
if ( $this->Application->RewriteURLs() || $rewrite_url ) {
// maybe call onafterconfigread here
$this->Application->UrlManager->initRewrite();
if ( defined('DEBUG_MODE') && $this->Application->isDebugMode() ) {
$this->Application->Debugger->profileStart('url_parsing', 'Parsing <b>MOD_REWRITE</b> url');
$this->Application->UrlManager->rewrite->parseRewriteURL();
$description = 'Parsing <b>MOD_REWRITE</b> url (template: <b>' . $this->Get('t') . '</b>)';
$this->Application->Debugger->profileFinish('url_parsing', $description);
}
else {
$this->Application->UrlManager->rewrite->parseRewriteURL();
}
if ( !$rewrite_url && $this->rewriteRedirectRequired() ) {
// rewrite url is missing (e.g. not a script from tools folder)
$url_params = $this->getRedirectParams();
// no idea about how to check, that given template require category to be passed with it, so pass anyway
$url_params['pass_category'] = 1;
$url_params['response_code'] = 301; // Moved Permanently
trigger_error('Non mod-rewrite url "<strong>' . $_SERVER['REQUEST_URI'] . '</strong>" used', E_USER_NOTICE);
$this->Application->Redirect('', $url_params);
}
if ( $this->Application->GetVar('is_friendly_url') ) {
$url_params = $this->getRedirectParams();
// No idea about how to check, that given template
// require category to be passed with it, so pass anyway.
$url_params['pass_category'] = 1;
$this->Application->Redirect('', $url_params);
}
}
else {
$this->Application->VerifyThemeId();
$this->Application->VerifyLanguageId();
}
$virtual_template = $this->Application->getVirtualPageTemplate($this->Get('m_cat_id'));
if ( ($virtual_template !== false) && preg_match('/external:(.*)/', $virtual_template) ) {
trigger_error('URL of page, that has "External URL" set was accessed: "<strong>' . $_SERVER['REQUEST_URI'] . '</strong>"', E_USER_NOTICE);
$this->Application->Redirect($virtual_template);
}
}
/**
* Checks, that non-rewrite url was visited and it's automatic rewrite is required
*
* @return bool
*/
function rewriteRedirectRequired()
{
$redirect_conditions = Array (
!$this->IsHTTPSRedirect(), // not https <-> http redirect
!$this->refererIsOurSite(), // referer doesn't match ssl path or non-ssl domain (same for site domains)
!defined('GW_NOTIFY'), // not in payment gateway notification script
preg_match('/[\/]{0,1}index.php[\/]{0,1}/', $_SERVER['PHP_SELF']), // "index.php" was visited
$this->Get('t') != 'index', // not on index page
);
$perform_redirect = true;
foreach ($redirect_conditions as $redirect_condition) {
$perform_redirect = $perform_redirect && $redirect_condition;
if (!$perform_redirect) {
return false;
}
}
return true;
}
/**
* This is redirect from https to http or via versa
*
* @return bool
*/
function IsHTTPSRedirect()
{
$http_referer = array_key_exists('HTTP_REFERER', $_SERVER) ? $_SERVER['HTTP_REFERER'] : false;
return (
( PROTOCOL == 'https://' && preg_match('#http:\/\/#', $http_referer) )
||
( PROTOCOL == 'http://' && preg_match('#https:\/\/#', $http_referer) )
);
}
/**
* Checks, that referer is out site
*
* @return bool
*/
function refererIsOurSite()
{
if ( !array_key_exists('HTTP_REFERER', $_SERVER) ) {
// no referer -> don't care what happens
return false;
}
/** @var SiteHelper $site_helper */
$site_helper = $this->Application->recallObject('SiteHelper');
$found = false;
$http_referer = $_SERVER['HTTP_REFERER'];
preg_match('/^(.*?):\/\/(.*?)(\/|$)/', $http_referer, $regs); // 1 - protocol, 2 - domain
if ($regs[1] == 'https') {
$found = $site_helper->getDomainByName('SSLUrl', $http_referer) > 0;
if (!$found) {
// check if referer starts with our ssl url
$ssl_url = $this->Application->ConfigValue('SSL_URL');
$found = $ssl_url && preg_match('/^' . preg_quote($ssl_url, '/') . '/', $http_referer);
}
}
else {
$found = $site_helper->getDomainByName('DomainName', $regs[2]) > 0;
if (!$found) {
$found = $regs[2] == DOMAIN;
}
}
return $found;
}
function convertFiles()
{
if ( !$_FILES ) {
return ;
}
$tmp = Array ();
$file_keys = Array ('error', 'name', 'size', 'tmp_name', 'type');
foreach ($_FILES as $file_name => $file_info) {
if ( is_array($file_info['error']) ) {
$tmp[$file_name] = $this->getArrayLevel($file_info['error'], $file_name);
}
else {
$normal_files[$file_name] = $file_info;
}
}
if ( !$tmp ) {
return ;
}
$files = $_FILES;
$_FILES = Array ();
foreach ($tmp as $prefix => $prefix_files) {
$anchor =& $_FILES;
foreach ($prefix_files['keys'] as $key) {
$anchor =& $anchor[$key];
}
foreach ($prefix_files['value'] as $field_name) {
unset($inner_anchor, $copy);
$work_copy = $prefix_files['keys'];
foreach ($file_keys as $file_key) {
$inner_anchor =& $files[$prefix][$file_key];
if ( isset($copy) ) {
$work_copy = $copy;
}
else {
$copy = $work_copy;
}
array_shift($work_copy);
foreach ($work_copy as $prefix_file_key) {
$inner_anchor =& $inner_anchor[$prefix_file_key];
}
$anchor[$field_name][$file_key] = $inner_anchor[$field_name];
}
}
}
// keys: img_temp, 0, values: LocalPath, ThumbPath
}
function getArrayLevel(&$level, $prefix='')
{
$ret['keys'] = $prefix ? Array($prefix) : Array();
$ret['value'] = Array();
foreach($level as $level_key => $level_value)
{
if( is_array($level_value) )
{
$ret['keys'][] = $level_key;
$tmp = $this->getArrayLevel($level_value);
$ret['keys'] = array_merge($ret['keys'], $tmp['keys']);
$ret['value'] = array_merge($ret['value'], $tmp['value']);
}
else
{
$ret['value'][] = $level_key;
}
}
return $ret;
}
/**
* Overwrites GET events with POST events in case if they are set and not empty
*
* @return void
* @access protected
*/
protected function convertPostEvents()
{
/** @var Array $events */
$events = $this->Get('events', Array ());
if ( is_array($events) ) {
$events = array_filter($events);
foreach ($events as $prefix_special => $event_name) {
$this->Set($prefix_special . '_event', $event_name);
}
}
}
function finalizeParsing($passed = Array())
{
if (!$passed) {
return;
}
foreach ($passed as $passed_prefix) {
$this->discoverUnit($passed_prefix); // from mod-rewrite url parsing
}
$this->Set('passed', implode(',', $this->getDiscoveredUnits()));
}
/**
* Saves variables from array specified
* into common variable storage place
*
* @param Array $array
* @param bool $strip_slashes
* @return Array
* @access private
*/
function AddVars($array, $strip_slashes = true)
{
if ( $strip_slashes ) {
$array = $this->StripSlashes($array);
}
foreach ($array as $key => $value) {
$this->Set($key, $value);
}
return $array;
}
function MergeVars($array, $strip_slashes = true)
{
if ( $strip_slashes ) {
$array = $this->StripSlashes($array);
}
foreach ($array as $key => $value_array) {
// $value_array is an array too
$this->_Params = kUtil::array_merge_recursive($this->_Params, Array ($key => $value_array));
}
return $array;
}
function StripSlashes($array)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = $this->StripSlashes($value);
}
else {
if (!$this->Application->isAdmin) {
// TODO: always escape output instead of input
$value = kUtil::escape($value, kUtil::ESCAPE_HTML);
}
$array[$key] = $value;
}
}
return $array;
}
/**
* Removes forceful escaping done to the variable upon Front-End submission.
*
* @param string|array $value Value.
*
* @return string|array
* @see StripSlashes
*/
public function unescapeRequestVariable($value)
{
if ( $this->Application->isAdmin ) {
return $value;
}
// This allows to revert kUtil::escape() call for each field submitted on front-end.
if ( is_array($value) ) {
foreach ( $value as $param_name => $param_value ) {
$value[$param_name] = $this->unescapeRequestVariable($param_value);
}
return $value;
}
return kUtil::unescape($value, kUtil::ESCAPE_HTML);
}
/**
* Returns all $_GET array excluding system parameters, that are not allowed to be passed through generated urls
*
* @param bool $access_error Method is called during no_permission, require login, session expiration link preparation
* @return Array
*/
function getRedirectParams($access_error = false)
{
$vars = $this->Get;
$unset_vars = Array (ENV_VAR_NAME, 'rewrite', '_mod_rw_url_', 'Action');
if (!$this->_sidInQueryString) {
$unset_vars[] = 'sid';
}
// remove system variables
foreach ($unset_vars as $var_name) {
if (array_key_exists($var_name, $vars)) {
unset($vars[$var_name]);
}
}
if ($access_error) {
// place 1 of 2 (also in UsersEventHandler::OnSessionExpire)
$vars = $this->_removePassThroughVariables($vars);
}
return $vars;
}
/**
* Removes all pass_though variables from redirect params
*
* @param Array $url_params
* @return Array
*/
function _removePassThroughVariables($url_params)
{
$pass_through = array_key_exists('pass_through', $url_params) ? $url_params['pass_through'] : '';
if (!$pass_through) {
return $url_params;
}
$pass_through = explode(',', $pass_through . ',pass_through');
foreach ($pass_through as $pass_through_var) {
unset($url_params[$pass_through_var]);
}
$url_params['no_pass_through'] = 1; // this way kApplication::HREF won't add them again
return $url_params;
}
/**
* Checks, that url is empty
*
* @return bool
* @access public
*/
public function isEmptyUrl()
{
if ( $this->Application->RewriteURLs() ) {
$url = $this->Get('_mod_rw_url_');
return !is_string($url) || !$url;
}
return !count($this->Get);
}
/**
* Returns the client IP address.
*
* @return string The client IP address
* @access public
*/
public function getClientIp()
{
if ( $this->_trustProxy ) {
if ( array_key_exists('HTTP_CLIENT_IP', $_SERVER) ) {
return $_SERVER['HTTP_CLIENT_IP'];
}
if ( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) ) {
$client_ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($client_ip as $ip_address) {
$clean_ip_address = trim($ip_address);
if ( false !== filter_var($clean_ip_address, FILTER_VALIDATE_IP) ) {
return $clean_ip_address;
}
}
return '';
}
}
return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
}
/**
* Returns headers
*
* @return array
* @access public
*/
public function getHeaders()
{
if ( function_exists('apache_request_headers') ) {
// If apache_request_headers() exists...
$headers = apache_request_headers();
if ( $headers !== false ) {
return $headers; // And works... Use it.
}
}
$headers = array();
$header_server_keys = array_filter(array_keys($_SERVER), function ($server_key) {
return strpos($server_key, 'HTTP_') === 0;
});
foreach ( $header_server_keys as $server_key ) {
$header_name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($server_key, 5)))));
$headers[$header_name] = $_SERVER[$server_key];
}
return $headers;
}
}
Index: branches/5.2.x/core/units/admin/admin_events_handler.php
===================================================================
--- branches/5.2.x/core/units/admin/admin_events_handler.php (revision 16803)
+++ branches/5.2.x/core/units/admin/admin_events_handler.php (revision 16804)
@@ -1,1386 +1,1385 @@
<?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 AdminEventsHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnSaveColumns' => Array ('self' => true),
'OnGetPopupSize' => Array ('self' => true),
'OnClosePopup' => Array ('self' => true),
'OnSaveSetting' => Array ('self' => true),
'OnProcessSelected' => Array ('self' => true), // allow CSV import file upload
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
$perm_value = null;
$system_events = array(
'OnResetModRwCache', 'OnResetSections', 'OnResetConfigsCache', 'OnResetParsedData', 'OnResetMemcache',
'OnDeleteCompiledTemplates', 'OnCompileTemplates', 'OnGenerateTableStructure', 'OnSynchronizeDBRevisions',
'OnDeploy', 'OnRebuildThemes', 'OnDumpAssets', 'OnCheckPrefixConfig', 'OnMemoryCacheGet',
'OnMemoryCacheSet',
);
if ( in_array($event->Name, $system_events) ) {
// events from "Tools -> System Tools" section are controlled via that section "edit" permission
$perm_value = /*$this->Application->isDebugMode() ||*/ $this->Application->CheckPermission($event->getSection() . '.edit');
}
$tools_events = Array (
'OnBackup' => 'in-portal:backup.view',
'OnBackupProgress' => 'in-portal:backup.view',
'OnDeleteBackup' => 'in-portal:backup.view',
'OnBackupCancel' => 'in-portal:backup.view',
'OnRestore' => 'in-portal:restore.view',
'OnRestoreProgress' => 'in-portal:restore.view',
'OnRestoreCancel' => 'in-portal:backup.view',
'OnSqlQuery' => 'in-portal:sql_query.view',
);
if ( array_key_exists($event->Name, $tools_events) ) {
$perm_value = $this->Application->CheckPermission($tools_events[$event->Name]);
}
if ( $event->Name == 'OnSaveMenuFrameWidth' || $event->Name == 'OnDropTempTablesByWID' ) {
$perm_value = $this->Application->isAdminUser;
}
/** @var kPermissionsHelper $perm_helper */
$perm_helper = $this->Application->recallObject('PermissionsHelper');
$csv_events = Array ('OnCSVImportBegin', 'OnCSVImportStep', 'OnExportCSV', 'OnGetCSV');
if ( in_array($event->Name, $csv_events) ) {
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$prefix = $csv_helper->getPrefix(stripos($event->Name, 'import') !== false);
$perm_mapping = Array (
'OnCSVImportBegin' => 'OnProcessSelected',
'OnCSVImportStep' => 'OnProcessSelected',
'OnExportCSV' => 'OnLoad',
'OnGetCSV' => 'OnLoad',
);
$tmp_event = new kEvent($prefix . ':' . $perm_mapping[$event->Name] );
$perm_value = $perm_helper->CheckEventPermission($tmp_event, $this->permMapping);
}
if ( isset($perm_value) ) {
return $perm_helper->finalizePermissionCheck($event, $perm_value);
}
return parent::CheckPermission($event);
}
/**
* Reset mod-rewrite url cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetModRwCache(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
$this->Conn->Query('DELETE FROM ' . TABLE_PREFIX . 'CachedUrls');
$event->SetRedirectParam('action_completed', 1);
}
/**
* Resets tree section cache and refreshes admin section tree
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetSections(kEvent $event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = kEvent::erSTOP;
}
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$this->Application->rebuildCache('master:sections_parsed', kCache::REBUILD_LATER, CacheSettings::$sectionsParsedRebuildTime);
}
else {
$this->Application->rebuildDBCache('sections_parsed', kCache::REBUILD_LATER, CacheSettings::$sectionsParsedRebuildTime);
}
$event->SetRedirectParam('refresh_tree', 1);
$event->SetRedirectParam('action_completed', 1);
}
/**
* Resets unit config cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetConfigsCache(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->rebuildCache('master:config_files', kCache::REBUILD_LATER, CacheSettings::$unitCacheRebuildTime);
}
else {
$this->Application->rebuildDBCache('config_files', kCache::REBUILD_LATER, CacheSettings::$unitCacheRebuildTime);
}
$this->OnResetParsedData($event);
/** @var SkinHelper $skin_helper */
$skin_helper = $this->Application->recallObject('SkinHelper');
$skin_helper->deleteCompiled();
}
/**
* Resets parsed data from unit configs
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetParsedData(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
$this->Application->DeleteUnitCache();
if ( $this->Application->GetVar('validate_configs') ) {
$event->SetRedirectParam('validate_configs', 1);
}
$event->SetRedirectParam('action_completed', 1);
}
/**
* Resets memory cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetMemcache(kEvent $event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = kEvent::erSTOP;
}
$this->Application->resetCache();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Compiles all templates (with a progress bar)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCompileTemplates(kEvent $event)
{
/** @var NParserCompiler $compiler */
$compiler = $this->Application->recallObject('NParserCompiler');
$compiler->CompileTemplatesStep();
$event->status = kEvent::erSTOP;
}
/**
* Deletes all compiled templates
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteCompiledTemplates(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
$base_path = WRITEABLE . DIRECTORY_SEPARATOR . 'cache';
// delete debugger reports
$debugger_reports = glob(RESTRICTED . '/debug_@*@.txt');
if ( $debugger_reports ) {
foreach ($debugger_reports as $debugger_report) {
unlink($debugger_report);
}
}
$this->_deleteCompiledTemplates($base_path);
$event->SetRedirectParam('action_completed', 1);
}
/**
* Deletes compiled templates in a given folder
*
* @param string $folder
* @param bool $unlink_folder
* @return void
* @access protected
*/
protected function _deleteCompiledTemplates($folder, $unlink_folder = false)
{
$sub_folders = glob($folder . '/*', GLOB_ONLYDIR);
if ( is_array($sub_folders) ) {
foreach ($sub_folders as $sub_folder) {
$this->_deleteCompiledTemplates($sub_folder, true);
}
}
$files = glob($folder . '/*.php');
if ( is_array($files) ) {
foreach ($files as $file) {
unlink($file);
}
}
if ( $unlink_folder ) {
rmdir($folder);
}
}
/**
* Generates structure for specified table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGenerateTableStructure(kEvent $event)
{
$types_hash = Array (
'string' => 'varchar|text|mediumtext|longtext|date|datetime|time|timestamp|char|year|enum|set',
'int' => 'smallint|mediumint|int|bigint|tinyint',
'float' => 'float|double|decimal',
);
$table_name = $this->Application->GetVar('table_name');
if ( !$table_name ) {
echo 'error: no table name specified';
return;
}
if ( TABLE_PREFIX && !preg_match('/^' . preg_quote(TABLE_PREFIX, '/') . '(.*)/', $table_name) && (strtolower($table_name) != $table_name) ) {
// table name without prefix, then add it (don't affect K3 tables named in lowercase)
$table_name = TABLE_PREFIX . $table_name;
}
if ( !$this->Conn->TableFound($table_name) ) {
// table with prefix doesn't exist, assume that just config prefix passed -> resolve table name from it
$prefix = preg_replace('/^' . preg_quote(TABLE_PREFIX, '/') . '/', '', $table_name);
if ( $this->Application->prefixRegistred($prefix) ) {
// when prefix is found -> use it's table (don't affect K3 tables named in lowecase)
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
}
}
$table_info = $this->Conn->Query('DESCRIBE '.$table_name);
// 1. prepare config keys
$grids = Array (
'Default' => Array (
'Icons' => Array ('default' => 'icon16_item.png'),
'Fields' => Array (),
)
);
$grids_fields = Array();
$id_field = '';
$fields = Array ();
$float_types = Array ('float', 'double', 'numeric');
foreach ($table_info as $field_info) {
if ( preg_match('/l[\d]+_.*/', $field_info['Field']) ) {
// don't put multilingual fields in config
continue;
}
$field_options = Array ();
if ( $field_info['Key'] == 'PRI' ) {
if ( $field_info['Field'] == 'Id' ) {
$grid_col_options = Array ('filter_block' => 'grid_range_filter', 'width' => 80);
}
else {
$grid_col_options = Array ('title' => 'column:la_fld_Id', 'filter_block' => 'grid_range_filter', 'width' => 80);
}
}
else {
$grid_col_options = Array ('filter_block' => 'grid_like_filter');
}
// 1. get php field type by mysql field type
foreach ($types_hash as $php_type => $db_types) {
if ( preg_match('/' . $db_types . '/', $field_info['Type']) ) {
$field_options['type'] = $php_type;
break;
}
}
// 2. get field default value
$default_value = $field_info['Default'];
$not_null = $field_info['Null'] != 'YES';
if ( is_numeric($default_value) ) {
$default_value = preg_match('/[\.,]/', $default_value) ? (float)$default_value : (int)$default_value;
}
if ( is_null($default_value) && $not_null ) {
$default_value = $field_options['type'] == 'string' ? '' : 0;
}
if ( in_array($php_type, $float_types) ) {
// this is float number
if ( preg_match('/' . $db_types . '\([\d]+,([\d]+)\)/i', $field_info['Type'], $regs) ) {
// size is described in structure -> add formatter
$field_options['formatter'] = 'kFormatter';
$field_options['format'] = '%01.' . $regs[1] . 'f';
if ( $not_null ) {
// null fields, will most likely have NULL as default value
$default_value = 0;
}
}
elseif ( $not_null ) {
// no size information, just convert to float
// null fields, will most likely have NULL as default value
$default_value = (float)$default_value;
}
}
if ( preg_match('/varchar\(([\d]+)\)/i', $field_info['Type'], $regs) ) {
$field_options['max_len'] = (int)$regs[1];
}
if ( preg_match('/tinyint\([\d]+\)/i', $field_info['Type']) ) {
$field_options['formatter'] = 'kOptionsFormatter';
$field_options['options'] = Array (1 => 'la_Yes', 0 => 'la_No');
$field_options['use_phrases'] = 1;
$grid_col_options['filter_block'] = 'grid_options_filter';
}
if ( $not_null ) {
$field_options['not_null'] = 1;
}
if ( $field_info['Key'] == 'PRI' ) {
$default_value = 0;
$id_field = $field_info['Field'];
}
if ( $php_type == 'int' && !$not_null ) {
// numeric null field
if ( preg_match('/(On|Date)$/', $field_info['Field']) || $field_info['Field'] == 'Modified' ) {
$field_options['formatter'] = 'kDateFormatter';
$grid_col_options['filter_block'] = 'grid_date_range_filter';
$grid_col_options['width'] = 120;
}
else {
$grid_col_options['filter_block'] = 'grid_range_filter';
$grid_col_options['width'] = 80;
}
}
if ( $php_type == 'int' && ($not_null || is_numeric($default_value)) ) {
// is integer field AND not null
$field_options['default'] = (int)$default_value;
}
else {
$field_options['default'] = $default_value;
}
$fields[$field_info['Field']] = $field_options;
$grids_fields[$field_info['Field']] = $grid_col_options;
}
$grids['Default']['Fields'] = $grids_fields;
$ret = Array (
'IDField' => $id_field,
'Fields' => $fields,
'Grids' => $grids,
);
$decorator = new UnitConfigDecorator();
$ret = $decorator->decorate($ret);
$this->Application->InitParser();
ob_start();
echo $this->Application->ParseBlock(Array('name' => 'incs/header', 'body_properties' => 'style="background-color: #E7E7E7; margin: 8px;"'));
?>
<script type="text/javascript">
set_window_title('Table "<?php echo $table_name; ?>" Structure');
</script>
<a href="javascript:window_close();">Close Window</a><br /><br />
<?php echo $GLOBALS['debugger']->highlightString($ret); ?>
<br /><br /><a href="javascript:window_close();">Close Window</a><br />
<?php
echo $this->Application->ParseBlock(Array('name' => 'incs/footer'));
echo ob_get_clean();
$event->status = kEvent::erSTOP;
}
/**
* Refreshes ThemeFiles & Themes tables by actual content on HDD
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRebuildThemes(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
/** @var kThemesHelper $themes_helper */
$themes_helper = $this->Application->recallObject('ThemesHelper');
$themes_helper->refreshThemes();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Dumps assets
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnDumpAssets(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
/** @var MinifyHelper $minify_helper */
$minify_helper = $this->Application->recallObject('MinifyHelper');
$minify_helper->delete();
$minify_helper->dump();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Saves grid column widths after their resize by user
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveColumns(kEvent $event)
{
$picker_helper = new kColumnPickerHelper(
$this->Application->GetVar('main_prefix'),
$this->Application->GetLinkedVar('grid_name')
);
$picked = trim($this->Application->GetVar('picked_str'), '|');
$hidden = trim($this->Application->GetVar('hidden_str'), '|');
$picker_helper->saveColumns($picked, $hidden);
$this->finalizePopup($event);
}
/**
* Saves various admin settings via ajax
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveSetting(kEvent $event)
{
if ( $this->Application->GetVar('ajax') != 'yes' ) {
return;
}
$var_name = $this->Application->GetVar('var_name');
$var_value = $this->Application->GetVar('var_value');
$this->Application->StorePersistentVar($var_name, $var_value);
$event->status = kEvent::erSTOP;
}
/**
* Just closes popup & deletes last_template & opener_stack if popup, that is closing
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnClosePopup(kEvent $event)
{
$event->SetRedirectParam('opener', 'u');
}
/**
* Occurs right after initialization of the kernel, used mainly as hook-to event
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnStartup(kEvent $event)
{
if ( $this->Application->isAdmin ) {
return;
}
$base_url = preg_quote($this->Application->BaseURL(), '/');
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if ( $referrer && !preg_match('/^' . $base_url . '/', $referrer) ) {
$this->Application->Session->SetCookie('original_referrer', $referrer);
- $this->Application->SetVar('original_referrer', $referrer);
}
}
/**
* Occurs right before echoing the output, in Done method of application, used mainly as hook-to event
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeShutdown(kEvent $event)
{
}
/**
* Is called after tree was build (when not from cache)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterBuildTree(kEvent $event)
{
}
/**
* Called by AJAX to perform CSV export
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnExportCSV(kEvent $event)
{
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$csv_helper->PrefixSpecial = $csv_helper->getPrefix(false);
$csv_helper->grid = $this->Application->GetVar('grid');
$csv_helper->ExportStep();
$event->status = kEvent::erSTOP;
}
/**
* Returning created by AJAX CSV file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGetCSV(kEvent $event)
{
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$csv_helper->GetCSV();
}
/**
* Start CSV import
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCSVImportBegin(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$object->setID(0);
$field_values = $this->getSubmittedFields($event);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$event->redirect = false;
$result = 'required';
if ( $object->GetDBField('ImportFile') ) {
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$csv_helper->PrefixSpecial = $csv_helper->getPrefix(true);
$csv_helper->grid = $this->Application->GetVar('grid');
$result = $csv_helper->ImportStart($object->GetField('ImportFile', 'file_paths'));
if ( $result === true ) {
$event->redirect = $this->Application->GetVar('next_template');
$event->SetRedirectParam('PrefixSpecial', $this->Application->GetVar('PrefixSpecial'));
$event->SetRedirectParam('grid', $this->Application->GetVar('grid'));
}
}
if ( $event->redirect === false ) {
$object->SetError('ImportFile', $result);
$event->status = kEvent::erFAIL;
}
}
/**
* Performs one CSV import step
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCSVImportStep(kEvent $event)
{
/** @var kCSVHelper $import_helper */
$import_helper = $this->Application->recallObject('CSVHelper');
$import_helper->ImportStep();
$event->status = kEvent::erSTOP;
}
/**
* Shows unit config filename, where requested prefix is defined
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCheckPrefixConfig(kEvent $event)
{
$prefix = $this->Application->GetVar('config_prefix');
$config_file = $this->Application->UnitConfigReader->prefixFiles[$prefix];
$this->Application->InitParser();
ob_start();
echo $this->Application->ParseBlock(Array('name' => 'incs/header', 'body_properties' => 'style="background-color: #E7E7E7; margin: 8px;"'));
?>
<script type="text/javascript">
set_window_title('Unit Config of "<?php echo $prefix; ?>" prefix');
</script>
<a href="javascript:window_close();">Close Window</a><br /><br />
<strong>Prefix:</strong> <?php echo $prefix; ?><br />
<strong>Unit Config:</strong> <?php echo $GLOBALS['debugger']->highlightString($config_file); ?><br />
<br /><a href="javascript:window_close();">Close Window</a><br />
<?php
echo $this->Application->ParseBlock(Array ('name' => 'incs/footer'));
echo ob_get_clean();
$event->status = kEvent::erSTOP;
}
/**
* Deletes temp tables, when user closes window using "x" button in top right corner
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDropTempTablesByWID(kEvent $event)
{
$sid = $this->Application->GetSID(Session::PURPOSE_REFERENCE);
$wid = $this->Application->GetVar('m_wid');
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/' . TABLE_PREFIX . 'ses_' . $sid . '_' . $wid . '_edit_(.*)$/';
foreach ($tables as $table) {
if ( preg_match($mask_edit_table, $table, $rets) ) {
$this->Conn->Query('DROP TABLE IF EXISTS ' . $table);
}
}
echo 'OK';
$event->status = kEvent::erSTOP;
}
/**
* Backup all data
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBackup(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
if ( !$backup_helper->initBackup() ) {
$event->status = kEvent::erFAIL;
}
$event->redirect = 'tools/backup2';
}
/**
* Perform next backup step
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBackupProgress(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$done_percent = $backup_helper->performBackup();
if ( $done_percent == 100 ) {
$event->redirect = 'tools/backup3';
return;
}
$event->status = kEvent::erSTOP;
echo $done_percent;
}
/**
* Stops Backup & redirect to Backup template
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBackupCancel(kEvent $event)
{
$event->redirect = 'tools/backup1';
}
/**
* Starts restore process
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRestore(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$backup_helper->initRestore();
$event->redirect = 'tools/restore3';
}
/**
* Performs next restore step
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRestoreProgress(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$done_percent = $backup_helper->performRestore();
if ( $done_percent == BackupHelper::SQL_ERROR_DURING_RESTORE ) {
$event->redirect = 'tools/restore4';
}
elseif ( $done_percent == BackupHelper::FAILED_READING_BACKUP_FILE ) {
$this->Application->StoreVar('adm.restore_error', 'File read error');
$event->redirect = 'tools/restore4';
}
elseif ( $done_percent == 100 ) {
$backup_helper->replaceRestoredFiles();
$this->Application->StoreVar('adm.restore_success', 1);
$event->redirect = 'tools/restore4';
}
else {
$event->status = kEvent::erSTOP;
echo $done_percent;
}
}
/**
* Stops Restore & redirect to Restore template
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRestoreCancel(kEvent $event)
{
$event->redirect = 'tools/restore1';
}
/**
* Deletes one backup file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteBackup(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$backup_helper->delete();
}
/**
* Starts restore process
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSqlQuery(kEvent $event)
{
$sql = $this->Application->GetVar('sql');
if ( $sql ) {
$start = microtime(true);
$result = $this->Conn->Query($sql);
$this->Application->SetVar('sql_time', round(microtime(true) - $start, 7));
if ( $result && is_array($result) ) {
$this->Application->SetVar('sql_has_rows', 1);
$this->Application->SetVar('sql_rows', serialize($result));
}
$check_sql = trim(strtolower($sql));
if ( preg_match('/^(insert|update|replace|delete)/', $check_sql) ) {
$this->Application->SetVar('sql_has_affected', 1);
$this->Application->SetVar('sql_affected', $this->Conn->getAffectedRows());
}
}
$this->Application->SetVar('query_status', 1);
$event->status = kEvent::erFAIL;
}
/**
* Occurs after unit config cache was successfully rebuilt
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterCacheRebuild(kEvent $event)
{
}
/**
* Removes "Community -> Groups" section when it is not allowed
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$section_adjustments = $this->Application->getUnitOption($event->Prefix, 'SectionAdjustments', Array());
if ( !$this->Application->ConfigValue('AdvancedUserManagement') ) {
$section_adjustments['in-portal:user_groups'] = 'remove';
}
$section_adjustments['in-portal:root'] = Array (
'label' => $this->Application->ConfigValue('Site_Name')
);
$this->Application->setUnitOption($event->Prefix, 'SectionAdjustments', $section_adjustments);
}
/**
* Saves menu (tree) frame width
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveMenuFrameWidth(kEvent $event)
{
$event->status = kEvent::erSTOP;
if ( !$this->Application->ConfigValue('ResizableFrames') ) {
return;
}
$this->Application->StorePersistentVar('MenuFrameWidth', (int)$this->Application->GetVar('width'));
}
/**
* Retrieves data from memory cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMemoryCacheGet(kEvent $event)
{
$event->status = kEvent::erSTOP;
$ret = Array ('message' => '', 'code' => 0); // 0 - ok, > 0 - error
$key = $this->Application->GetVar('key');
if ( !$key ) {
$ret['code'] = 1;
$ret['message'] = 'Key name missing';
}
else {
$value = $this->Application->getCache($key);
$ret['value'] =& $value;
$ret['size'] = is_string($value) ? kUtil::formatSize(strlen($value)) : '?';
$ret['type'] = gettype($value);
if ( kUtil::IsSerialized($value) ) {
$value = unserialize($value);
}
if ( is_array($value) ) {
$ret['value'] = print_r($value, true);
}
if ( $ret['value'] === false ) {
$ret['code'] = 2;
$ret['message'] = 'Key "' . $key . '" doesn\'t exist';
}
}
/** @var JSONHelper $json_helper */
$json_helper = $this->Application->recallObject('JSONHelper');
echo $json_helper->encode($ret);
}
/**
* Retrieves data from memory cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMemoryCacheSet(kEvent $event)
{
$event->status = kEvent::erSTOP;
$ret = Array ('message' => '', 'code' => 0); // 0 - ok, > 0 - error
$key = $this->Application->GetVar('key');
if ( !$key ) {
$ret['code'] = 1;
$ret['message'] = 'Key name missing';
}
else {
$value = $this->Application->GetVar('value');
$res = $this->Application->setCache($key, $value);
$ret['result'] = $res ? 'OK' : 'FAILED';
}
/** @var JSONHelper $json_helper */
$json_helper = $this->Application->recallObject('JSONHelper');
echo $json_helper->encode($ret);
}
/**
* Deploy changes
*
* Usage: "php tools/run_event.php adm:OnDeploy b674006f3edb1d9cd4d838c150b0567d"
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeploy(kEvent $event)
{
$this->_deploymentAction($event);
}
/**
* Synchronizes database revisions from "project_upgrades.sql" file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSynchronizeDBRevisions(kEvent $event)
{
$this->_deploymentAction($event, true);
}
/**
* Common code to invoke deployment helper
*
* @param kEvent $event
* @param bool $dry_run
* @return void
* @access protected
*/
protected function _deploymentAction(kEvent $event, $dry_run = false)
{
/** @var DeploymentHelper $deployment_helper */
$deployment_helper = $this->Application->recallObject('DeploymentHelper');
$deployment_helper->setEvent($event);
if ( $deployment_helper->deployAll($dry_run) ) {
$event->SetRedirectParam('action_completed', 1);
if ( !$deployment_helper->isCommandLine ) {
// browser invocation -> don't perform redirect
$event->redirect = false;
// no redirect, but deployment succeeded - set redirect params directly
foreach ($event->getRedirectParams() as $param_name => $param_value) {
$this->Application->SetVar($param_name, $param_value);
}
}
}
else {
$event->status = kEvent::erFAIL;
}
}
/**
* [SCHEDULED TASK]
* 1. Delete all Debug files from system/.restricted folder (format debug_@f353wfsds43g5...@.txt)
* 2. Run MySQL OPTIMIZE SQL one by one on all In-Portal tables (found by prefix).
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnOptimizePerformance(kEvent $event)
{
$start_time = adodb_mktime();
$sql = 'SELECT SessionKey
FROM ' . TABLE_PREFIX . 'UserSessions
WHERE LastAccessed > ' . $start_time;
$active_sessions = array_flip($this->Conn->GetCol($sql));
$files = scandir(RESTRICTED);
$file_path = RESTRICTED . '/';
foreach ( $files as $file_name ) {
if ( !preg_match('#^debug_@([^@]+)@.txt$#', $file_name, $matches) ) {
// Not debug file.
continue;
}
$sid = $matches[1];
if ( isset($active_sessions[$sid]) || (filemtime($file_path . $file_name) > $start_time) ) {
// debug file belongs to an active session
// debug file is recently created (after sessions snapshot)
continue;
}
unlink($file_path . $file_name);
}
$system_tables = $this->Conn->GetCol('SHOW TABLES LIKE "' . TABLE_PREFIX . '%"');
foreach ($system_tables AS $table_name) {
$this->Conn->Query('OPTIMIZE TABLE ' . $table_name);
}
}
/**
* Returns popup size (by template), if not cached, then parse template to get value
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGetPopupSize(kEvent $event)
{
$event->status = kEvent::erSTOP;
if ( $this->Application->GetVar('ajax') != 'yes' ) {
return;
}
$t = $this->Application->GetVar('template_name');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'PopupSizes
WHERE TemplateName = ' . $this->Conn->qstr($t);
$popup_info = $this->Conn->GetRow($sql);
$this->Application->setContentType('text/plain');
if ( !$popup_info ) {
// dies when SetPopupSize tag found & in ajax request
$this->Application->InitParser();
$this->Application->ParseBlock(Array ('name' => $t));
// tag SetPopupSize not found in template -> use default size
echo '750x400';
}
else {
echo $popup_info['PopupWidth'] . 'x' . $popup_info['PopupHeight'];
}
}
/**
* Writes HTTP request to System Log
*
* @param kEvent $event
* @return void
* @access public
*/
public function OnLogHttpRequest(kEvent $event)
{
if ( defined('DBG_REQUEST_LOG') && DBG_REQUEST_LOG && $this->Application->LoggedIn() ) {
$log = $this->Application->log('HTTP_REQUEST')->addRequestData();
if ( !$log->write() ) {
trigger_error('Unable to log Http Request due disabled "System Log"', E_USER_WARNING);
}
}
}
/**
* Purges expired database cache entries.
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnPurgeExpiredDatabaseCacheScheduledTask(kEvent $event)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
WHERE LifeTime > 0 AND Cached + LifeTime < ' . time();
$this->Conn->Query($sql);
}
/**
* Populates URL unit cache
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnPopulateUrlUnitCacheScheduledTask(kEvent $event)
{
$sql = 'SELECT DISTINCT Prefixes
FROM ' . TABLE_PREFIX . 'CachedUrls';
$urls = $this->Conn->GetColIterator($sql);
$prefixes = array();
foreach ( $urls as $url_prefixes ) {
$url_prefixes = explode('|', trim($url_prefixes, '|'));
foreach ( $url_prefixes as $url_prefix ) {
$url_prefix = explode(':', $url_prefix);
$prefixes[$url_prefix[0]] = 1;
}
}
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->setCache('cached_urls_unit_prefixes', array_keys($prefixes), 3600);
}
else {
$this->Application->setDBCache('cached_urls_unit_prefixes', serialize(array_keys($prefixes)), 3600);
}
}
/**
* Deletes stuck semaphore records.
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnDeleteStuckSemaphoresScheduledTask(kEvent $event)
{
$semaphore_lifetime = $this->Application->ConfigValue('SemaphoreLifetimeInSeconds');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Semaphores
WHERE Timestamp < ' . strtotime('-' . $semaphore_lifetime . ' seconds');
$stuck_semaphores = $this->Conn->Query($sql, 'SemaphoreId');
if ( !$stuck_semaphores ) {
return;
}
/** @var LanguagesItem $language */
$language = $this->Application->recallObject('lang.current', null, array('skip_autoload' => true));
$date_format = $language->GetDBField('DateFormat') . ' ' . $language->GetDBField('TimeFormat');
foreach ( $stuck_semaphores as $semaphore_id => $semaphore_data ) {
$log = $this->Application->log('Stuck semaphore detected (unit: ' . $semaphore_data['MainPrefix'] . ')');
$log->setLogLevel(kLogger::LL_ERROR);
$log->addTrace(unserialize($semaphore_data['Backtrace']));
$log->setUserData(implode(PHP_EOL, array(
'Main Prefix: ' . $semaphore_data['MainPrefix'],
'Main IDs: ' . $semaphore_data['MainIDs'],
'Created On: ' . date($date_format, $semaphore_data['Timestamp']),
'Deleted On: ' . date($date_format),
)));
$log->setLogField('LogHostname', $semaphore_data['Hostname']);
$log->setLogField('LogRequestSource', 1); // Web.
$log->setLogField('LogInterface', kLogger::LI_ADMIN);
$log->setLogField('LogRequestURI', $semaphore_data['RequestURI']);
$log->setLogField('LogUserId', $semaphore_data['UserId']);
$log->setLogField('IpAddress', $semaphore_data['IpAddress']);
$log->setLogField('LogSessionKey', $semaphore_data['SessionKey']);
$log->write();
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Semaphores
WHERE SemaphoreId = ' . $semaphore_id;
$this->Conn->Query($sql);
}
}
}
class UnitConfigDecorator {
var $parentPath = Array ();
/**
* Decorates given array
*
* @param Array $var
* @param int $level
* @return string
*/
public function decorate($var, $level = 0)
{
$ret = '';
$deep_level = count($this->parentPath);
if ( $deep_level && ($this->parentPath[0] == 'Fields') ) {
$expand = $level < 2;
}
elseif ( $deep_level && ($this->parentPath[0] == 'Grids') ) {
if ( $deep_level == 3 && $this->parentPath[2] == 'Icons' ) {
$expand = false;
}
else {
$expand = $level < 4;
}
}
else {
$expand = $level == 0;
}
if ( is_array($var) ) {
$ret .= 'array(';
$prepend = $expand ? "\n" . str_repeat("\t", $level + 1) : '';
foreach ($var as $key => $value) {
array_push($this->parentPath, $key);
$ret .= $prepend . (is_string($key) ? "'" . $key . "'" : $key) . ' => ' . $this->decorate($value, $level + 1);
$ret .= ',' . ($expand ? '' : ' ');
array_pop($this->parentPath);
}
$prepend = $expand ? "\n" . str_repeat("\t", $level) : '';
if ( !$expand ) {
$ret = rtrim($ret, ', ');
}
$ret .= $prepend . ')';
}
else {
if ( is_null($var) ) {
$ret = 'null';
}
elseif ( is_string($var) ) {
$ret = "'" . $var . "'";
}
else {
$ret = $var;
}
}
return $ret;
}
}
Index: branches/5.2.x/core/units/forms/form_submissions/form_submissions_eh.php
===================================================================
--- branches/5.2.x/core/units/forms/form_submissions/form_submissions_eh.php (revision 16803)
+++ branches/5.2.x/core/units/forms/form_submissions/form_submissions_eh.php (revision 16804)
@@ -1,552 +1,552 @@
<?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 FormSubmissionsEventHandler extends kDBEventHandler {
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
if ( !$this->Application->isAdmin ) {
if ( $event->Name == 'OnCreate' ) {
// anybody can submit forms on front
return true;
}
}
$section = $event->getSection();
$form_id = $this->Application->GetVar('form_id');
$event->setEventParam('PermSection', $section . ':' . $form_id);
return parent::CheckPermission($event);
}
/**
* Always allow to view feedback form
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnItemBuild' => Array ('self' => true),
'OnEdit' => Array ('self' => 'view', 'subitem' => 'view'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Returns filter block based on field element type
*
* @param string $element_type
* @return string
*/
function _getFilterBlock($element_type)
{
$mapping = Array (
'text' => 'grid_like_filter',
'select' => 'grid_options_filter',
'radio' => 'grid_options_filter',
'checkbox' => 'grid_options_filter',
'password' => 'grid_like_filter',
'textarea' => 'grid_like_filter',
'label' => 'grid_like_filter',
'upload' => 'grid_empty_filter',
);
return $mapping[$element_type];
}
function OnBuildFormFields($event)
{
$form_id = $this->Application->GetVar('form_id');
if (!$form_id) return ;
$conf_fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$conf_grids = $this->Application->getUnitOption($event->Prefix, 'Grids');
/** @var InpCustomFieldsHelper $helper */
$helper = $this->Application->recallObject('InpCustomFieldsHelper');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'FormFields
WHERE FormId = ' . (int)$form_id . '
ORDER BY Priority DESC';
$fields = $this->Conn->Query($sql, 'FormFieldId');
$use_options = Array ('radio', 'select', 'checkbox');
$check_visibility = $this->Application->LoggedIn() && !$this->Application->isAdminUser;
foreach ($fields as $field_id => $options) {
$field_visible = $check_visibility ? $options['Visibility'] == SubmissionFormField::VISIBILITY_EVERYONE : true;
$field_options = Array('type' => 'string', 'default' => $options['DefaultValue']);
if ($options['Required'] && $field_visible) {
$field_options['required'] = 1;
}
if ($options['Validation'] == 1) {
$field_options['formatter'] = 'kFormatter';
$field_options['regexp'] = '/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i';
}
if ($options['DisplayInGrid']) {
$title = $options['Prompt'];
if (substr($title, 0, 1) == '+') {
$this->Application->Phrases->AddCachedPhrase('form_col_title' . $field_id, substr($title, 1));
$title = 'form_col_title' . $field_id;
}
$conf_grids['Default']['Fields']['fld_' . $field_id] = Array (
'title' => $title, 'no_special' => 1, 'nl2br' => 1, 'first_chars' => 200,
'filter_block' => $this->_getFilterBlock($options['ElementType'])
);
if ($options['ElementType'] == 'upload') {
$conf_grids['Default']['Fields']['fld_' . $field_id]['data_block'] = 'grid_upload_td';
}
if ($options['Validation'] == 1) {
$conf_grids['Default']['Fields']['fld_' . $field_id]['data_block'] = 'grid_email_td';
}
}
if ($options['ElementType'] == 'checkbox' && !$options['ValueList']) {
// fix case, when user haven't defined any options for checkbox
$options['ValueList'] = '1=la_Yes||0=la_No';
}
if (in_array($options['ElementType'], $use_options) && $options['ValueList']) {
// field type can have options and user have defined them too
$field_options['options'] = $helper->GetValuesHash( $options['ValueList'] );
$field_options['formatter'] = 'kOptionsFormatter';
}
if ($options['ElementType'] == 'password') {
$field_options['formatter'] = 'kPasswordFormatter';
$field_options['hashing_method'] = PasswordHashingMethod::NONE;
$field_options['verify_field'] = 'fld_' . $field_id . '_verify';
}
if ($options['ElementType'] == 'upload') {
$field_options['formatter'] = 'kUploadFormatter';
$field_options['upload_dir'] = WRITEBALE_BASE . DIRECTORY_SEPARATOR . 'user_files' . DIRECTORY_SEPARATOR . 'form_submissions';
if ( $options['UploadMaxSize'] ) {
$field_options['max_size'] = $options['UploadMaxSize'] * 1024; // convert Kbytes to bytes
}
if ( $options['UploadExtensions'] ) {
$field_options['file_types'] = '*.' . implode(';*.', explode(',', $options['UploadExtensions']));
}
}
$conf_fields['fld_' . $field_id] = $field_options;
}
$this->Application->setUnitOption($event->Prefix, 'Fields', $conf_fields);
$this->Application->setUnitOption($event->Prefix, 'Grids', $conf_grids);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
/** @var kDBList $object */
$object = $event->getObject();
$object->addFilter('form_filter', '%1$s.FormId = ' . (int)$this->Application->GetVar('form_id'));
}
/**
* Allows user to see it's last feedback form data
*
* @param kEvent $event
* @return int
* @access public
*/
public function getPassedID(kEvent $event)
{
if ( $event->Special == 'last' ) {
// allow user to see his last submitted form
return $this->Application->RecallVar('last_submission_id');
}
if ( $this->Application->isAdminUser ) {
// don't check ids in admin
return parent::getPassedID($event);
}
// no way to see other user's form submission by giving it's ID directly in url
return 0;
}
/**
* Creates new form submission from Front-End
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCreate(kEvent $event)
{
parent::OnCreate($event);
if ( $event->status != kEvent::erSUCCESS ) {
return;
}
/** @var kDBItem $object */
$object = $event->getObject();
// allows user to view only it's last submission
$this->Application->StoreVar('last_submission_id', $object->GetID());
/** @var FormSubmissionHelper $form_submission_helper */
$form_submission_helper = $this->Application->recallObject('FormSubmissionHelper');
$form =& $form_submission_helper->getForm($object);
$notify_email = $form->GetDBField('SubmitNotifyEmail');
if ( $notify_email ) {
$send_params = Array (
'to_name' => $notify_email,
'to_email' => $notify_email,
);
$this->Application->emailAdmin('FORM.SUBMITTED', null, $send_params);
}
else {
$this->Application->emailAdmin('FORM.SUBMITTED');
}
// $this->Application->emailUser('FORM.SUBMITTED', null, Array ('to_email' => ''));
$event->SetRedirectParam('opener', 's');
$event->SetRedirectParam('m_cat_id', 0);
/** @var kDBItem $theme */
$theme = $this->Application->recallObject('theme.current');
$template = $this->Application->unescapeRequestVariable($this->Application->GetVar('success_template'));
$alias_template = $theme->GetField('TemplateAliases', $template);
$event->redirect = $alias_template ? $alias_template : $template;
}
/**
* Processes Captcha code
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
/** @var kDBItem $object */
$object = $event->getObject();
$object->SetDBField('IPAddress', $this->Application->getClientIp());
if ( !$object->GetDBField('ReferrerURL') ) {
- $referrer = $this->Application->GetVar('original_referrer');
+ $referrer = $this->Application->GetVarDirect('original_referrer', 'Cookie');
if ( !$referrer ) {
$base_url = preg_quote($this->Application->BaseURL(), '/');
$referrer = preg_replace('/^' . $base_url . '/', '/', $_SERVER['HTTP_REFERER'], 1);
}
$object->SetDBField('ReferrerURL', $referrer);
}
/** @var FormSubmissionHelper $form_submission_helper */
$form_submission_helper = $this->Application->recallObject('FormSubmissionHelper');
$form =& $form_submission_helper->getForm($object);
// validate captcha code
if ( $form->GetDBField('UseSecurityImage') && !$this->Application->LoggedIn() ) {
/** @var kCaptchaHelper $captcha_helper */
$captcha_helper = $this->Application->recallObject('CaptchaHelper');
$captcha_helper->validateCode($event, false);
}
}
/**
* Checks, that target submission was selected for merging
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
/** @var kDBItem $object */
$object = $event->getObject();
$object->setRequired('MergeToSubmission', $object->GetDBField('IsMergeToSubmission'));
}
/**
* Passes form_id, when using "Prev"/"Next" toolbar buttons
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveAndGo(kEvent $event)
{
parent::OnPreSaveAndGo($event);
if ( $event->status == kEvent::erSUCCESS ) {
$event->SetRedirectParam('pass', 'm,form,formsubs');
}
}
/**
* Saves edited item in temp table and goes
* to passed tabs, by redirecting to it with OnPreSave event
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveAndGoToTab(kEvent $event)
{
parent::OnPreSaveAndGoToTab($event);
if ( $event->status == kEvent::erSUCCESS ) {
$event->SetRedirectParam('pass', 'm,form,formsubs');
}
}
/**
* Set's new per-page for grid
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetPerPage(kEvent $event)
{
parent::OnSetPerPage($event);
$event->SetRedirectParam('pass', 'm,form,' . $event->getPrefixSpecial());
}
/**
* Occurs when page is changed (only for hooking)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetPage(kEvent $event)
{
parent::OnSetPage($event);
$event->SetRedirectParam('pass', 'm,form,' . $event->getPrefixSpecial());
}
/**
* Fills merge-to dropdown
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
if ($event->Special == 'merge-to') {
return ;
}
/** @var kDBItem $object */
$object = $event->getObject();
$form_id = $object->GetDBField('FormId');
$email_field = $this->getFieldByRole($form_id, SubmissionFormField::COMMUNICATION_ROLE_EMAIL);
if (!$email_field) {
return ;
}
/** @var kDBItem $merge_to */
$merge_to = $this->Application->recallObject($event->Prefix . '.merge-to', null, Array ('skip_autoload' => true));
$sql = $merge_to->GetSelectSQL() . ' WHERE (FormId = ' . $form_id . ') AND (' . $email_field . ' = ' . $this->Conn->qstr( $object->GetDBField($email_field) ) . ')';
$submissions = $this->Conn->Query($sql, $object->IDField);
// remove this submission
unset($submissions[ $object->GetID() ]);
if (!$submissions) {
return ;
}
$options = Array ();
$name_field = $this->getFieldByRole($form_id, SubmissionFormField::COMMUNICATION_ROLE_NAME);
$subject_field = $this->getFieldByRole($form_id, SubmissionFormField::COMMUNICATION_ROLE_SUBJECT);
/** @var kDBItem $language */
$language = $this->Application->recallObject('lang.current');
$date_format = $language->GetDBField('DateFormat');
foreach ($submissions as $submission_id => $submission_data) {
$option_title = ''; // SenderName (email@address.com) - Subject (06/29/2010)
$merge_to->LoadFromHash($submission_data);
if ($name_field) {
$option_title = $merge_to->GetDBField($name_field) . ' (' . $merge_to->GetDBField($email_field) . ') - ';
}
else {
$option_title = $merge_to->GetDBField($email_field) . ' - ';
}
if ($subject_field) {
$option_title .= $merge_to->GetField($subject_field) . ' (' . $merge_to->GetField('SubmissionTime', $date_format) . ')';
}
else {
$option_title .= $merge_to->GetField('SubmissionTime', $date_format);
}
$options[$submission_id] = $option_title;
}
$object->SetFieldOption('MergeToSubmission', 'options', $options);
}
/**
* Returns submission field name based on given role
*
* @param int $form_id
* @param string $role
* @return string
*/
function getFieldByRole($form_id, $role)
{
static $cache = Array ();
if (!array_key_exists($form_id, $cache)) {
$id_field = $this->Application->getUnitOption('formflds', 'IDField');
$table_name = $this->Application->getUnitOption('formflds', 'TableName');
$sql = 'SELECT ' . $id_field . ', EmailCommunicationRole
FROM ' . $table_name . '
WHERE FormId = ' . $form_id . ' AND EmailCommunicationRole <> 0';
$cache[$form_id] = $this->Conn->GetCol($sql, 'EmailCommunicationRole');
}
// get field name by role
return array_key_exists($role, $cache[$form_id]) ? 'fld_' . $cache[$form_id][$role] : false;
}
/**
* Performs submission merge
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdate(kEvent $event)
{
parent::OnUpdate($event);
if ($event->status == kEvent::erSUCCESS) {
/** @var kDBItem $object */
$object = $event->getObject();
$merge_to = $object->GetDBField('MergeToSubmission');
if (!$merge_to) {
return ;
}
$form_id = $object->GetDBField('FormId');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Forms
WHERE FormId = ' . $form_id;
$form_info = $this->Conn->GetRow($sql);
/** @var kDBItem $reply */
$reply = $this->Application->recallObject('submission-log.merge', null, Array ('skip_autoload' => true));
$email_field = $this->getFieldByRole($form_id, SubmissionFormField::COMMUNICATION_ROLE_EMAIL);
$subject_field = $this->getFieldByRole($form_id, SubmissionFormField::COMMUNICATION_ROLE_SUBJECT);
$body_field = $this->getFieldByRole($form_id, SubmissionFormField::COMMUNICATION_ROLE_BODY);
$reply->SetDBField('FormSubmissionId', $merge_to);
if ($email_field) {
$reply->SetDBField('FromEmail', $object->GetDBField($email_field));
}
$reply->SetDBField('ToEmail', $form_info['ReplyFromEmail']);
if ($subject_field) {
$reply->SetDBField('Subject', $object->GetDBField($subject_field));
}
if ($body_field) {
$reply->SetDBField('Message', $object->GetDBField($body_field));
}
$reply->SetDBField('SentOn_date', $object->GetDBField('SubmissionTime'));
$reply->SetDBField('SentOn_time', $object->GetDBField('SubmissionTime'));
$reply->SetDBField('MessageId', $object->GetDBField('MessageId'));
$reply->SetDBField('SentStatus', SUBMISSION_LOG_SENT);
// as if emails was really received via mailbox
$this->Application->SetVar('client_mode', 1);
if ($reply->Create()) {
// delete submission, since it was merged
$object->Delete();
}
}
}
}
Index: branches/5.2.x/core/units/helpers/user_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/user_helper.php (revision 16803)
+++ branches/5.2.x/core/units/helpers/user_helper.php (revision 16804)
@@ -1,755 +1,751 @@
<?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 UserHelper extends kHelper {
/**
* Event to be used during login processings
*
* @var kEvent
*/
var $event = null;
/**
* Performs user login and returns the result
*
* @param string $username
* @param string $password
* @param bool $dry_run
* @param bool $remember_login
* @param string $remember_login_cookie
* @return int
*/
function loginUser($username, $password, $dry_run = false, $remember_login = false, $remember_login_cookie = '')
{
if ( !isset($this->event) ) {
$this->event = new kEvent('u:OnLogin');
}
if ( (!$username || !$password) && !$remember_login_cookie ) {
return LoginResult::INVALID_PASSWORD;
}
$object =& $this->getUserObject();
// process "Save Username" checkbox
if ( $this->Application->isAdmin ) {
$save_username = $this->Application->GetVar('cb_save_username') ? $username : '';
$this->Application->Session->SetCookie('save_username', $save_username, strtotime('+1 year'));
-
- // cookie will be set on next refresh, but refresh won't occur if
- // login error present, so duplicate cookie in kHTTPQuery
- $this->Application->SetVar('save_username', $save_username);
}
// logging in "root" (admin only)
$super_admin = ($username == 'super-root') && $this->verifySuperAdmin();
if ( $this->Application->isAdmin && ($username == 'root') || ($super_admin && $username == 'super-root') ) {
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
if ( !$password_formatter->checkPasswordFromSetting('RootPass', $password) ) {
return LoginResult::INVALID_PASSWORD;
}
$user_id = USER_ROOT;
$object->Clear($user_id);
$object->SetDBField('Username', 'root');
if ( !$dry_run ) {
$this->loginUserById($user_id, $remember_login_cookie);
if ( $super_admin ) {
$this->Application->StoreVar('super_admin', 1);
}
// reset counters
$this->Application->resetCounters('UserSessions');
$this->_processLoginRedirect('root', $password);
$this->_processInterfaceLanguage();
$this->_fixNextTemplate();
}
return LoginResult::OK;
}
$user_id = $this->getUserId($username, $password, $remember_login_cookie);
if ( $user_id ) {
$object->Load($user_id);
if ( !$this->checkBanRules($object) ) {
return LoginResult::BANNED;
}
if ( $object->GetDBField('Status') == STATUS_ACTIVE ) {
if ( !$this->checkLoginPermission() ) {
return LoginResult::NO_PERMISSION;
}
if ( !$dry_run ) {
$this->loginUserById($user_id, $remember_login_cookie);
if ( $remember_login ) {
// remember username & password when "Remember Login" checkbox us checked (when user is using login form on Front-End)
$sql = 'SELECT MD5(Password)
FROM ' . TABLE_PREFIX . 'Users
WHERE PortalUserId = ' . $user_id;
$remember_login_hash = $this->Conn->GetOne($sql);
$this->Application->Session->SetCookie('remember_login', $username . '|' . $remember_login_hash, strtotime('+1 month'));
}
if ( !$remember_login_cookie ) {
// reset counters
$this->Application->resetCounters('UserSessions');
$this->_processLoginRedirect($username, $password);
$this->_processInterfaceLanguage();
$this->_fixNextTemplate();
}
}
return LoginResult::OK;
}
else {
$pending_template = $this->Application->GetVar('pending_disabled_template');
if ( $pending_template !== false && !$dry_run ) {
// when user found, but it's not yet approved redirect hit to notification template
$this->event->redirect = $pending_template;
return LoginResult::OK;
}
else {
// when no notification template given return an error
return LoginResult::INVALID_PASSWORD;
}
}
}
if ( !$dry_run ) {
$this->event->SetRedirectParam('pass', 'all');
// $this->event->SetRedirectParam('pass_category', 1); // to test
}
return LoginResult::INVALID_PASSWORD;
}
/**
* Login user by it's id
*
* @param int $user_id
* @param bool $remember_login_cookie
*/
function loginUserById($user_id, $remember_login_cookie = false)
{
$object =& $this->getUserObject();
$this->Application->SetVar('u.current_id', $user_id);
if ( !$this->Application->isAdmin ) {
// needed for "profile edit", "registration" forms ON FRONT ONLY
$this->Application->SetVar('u_id', $user_id);
}
$this->Application->StoreVar('user_id', $user_id);
$this->Application->Session->SetField('PortalUserId', $user_id);
if ($user_id != USER_ROOT) {
$groups = $this->Application->RecallVar('UserGroups');
list ($first_group, ) = explode(',', $groups);
$this->Application->Session->SetField('GroupId', $first_group);
$this->Application->Session->SetField('GroupList', $groups);
$this->Application->Session->SetField('TimeZone', $object->GetDBField('TimeZone'));
}
$this->Application->LoadPersistentVars();
if (!$remember_login_cookie) {
// don't change last login time when auto-login is used
$this_login = (int)$this->Application->RecallPersistentVar('ThisLogin');
$this->Application->StorePersistentVar('LastLogin', $this_login);
$this->Application->StorePersistentVar('ThisLogin', adodb_mktime());
}
$this->Application->Session->SaveData();
$hook_event = new kEvent('u:OnAfterLogin');
$hook_event->MasterEvent = $this->event;
$this->Application->HandleEvent($hook_event);
}
/**
* Checks login permission
*
* @return bool
*/
function checkLoginPermission()
{
$object =& $this->getUserObject();
$ip_restrictions = $object->GetDBField('IPRestrictions');
if ( $ip_restrictions && !$this->Application->isDebugMode() && !kUtil::ipMatch($ip_restrictions, "\n") ) {
return false;
}
$groups = $object->getMembershipGroups(true);
if ( !$groups ) {
$groups = Array ();
}
$default_group = $this->getUserTypeGroup();
if ( $default_group !== false ) {
array_push($groups, $default_group);
}
// store groups, because kApplication::CheckPermission will use them!
array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup'));
$groups = array_unique($groups);
$this->Application->StoreVar('UserGroups', implode(',', $groups), true); // true for optional
return $this->Application->CheckPermission($this->Application->isAdmin ? 'ADMIN' : 'LOGIN', 1);
}
/**
* Returns default user group for it's type
*
* @return bool|string
* @access protected
*/
protected function getUserTypeGroup()
{
$group_id = false;
$object =& $this->getUserObject();
if ( $object->GetDBField('UserType') == UserType::USER ) {
$group_id = $this->Application->ConfigValue('User_NewGroup');
}
elseif ( $object->GetDBField('UserType') == UserType::ADMIN ) {
$group_id = $this->Application->ConfigValue('User_AdminGroup');
}
$ip_restrictions = $this->getGroupsWithIPRestrictions();
if ( !isset($ip_restrictions[$group_id]) || kUtil::ipMatch($ip_restrictions[$group_id], "\n") ) {
return $group_id;
}
return false;
}
/**
* Returns groups with IP restrictions
*
* @return Array
* @access public
*/
public function getGroupsWithIPRestrictions()
{
static $cache = null;
if ( $this->Application->isDebugMode() ) {
return Array ();
}
if ( !isset($cache) ) {
$sql = 'SELECT IPRestrictions, GroupId
FROM ' . TABLE_PREFIX . 'UserGroups
WHERE COALESCE(IPRestrictions, "") <> ""';
$cache = $this->Conn->GetCol($sql, 'GroupId');
}
return $cache;
}
/**
* Performs user logout
*
*/
function logoutUser()
{
if (!isset($this->event)) {
$this->event = new kEvent('u:OnLogout');
}
$hook_event = new kEvent('u:OnBeforeLogout');
$hook_event->MasterEvent = $this->event;
$this->Application->HandleEvent($hook_event);
$this->_processLoginRedirect();
$user_id = USER_GUEST;
$this->Application->SetVar('u.current_id', $user_id);
/** @var UsersItem $object */
$object = $this->Application->recallObject('u.current', null, Array('skip_autoload' => true));
$object->Load($user_id);
$this->Application->DestroySession();
$this->Application->StoreVar('user_id', $user_id, true);
$this->Application->Session->SetField('PortalUserId', $user_id);
$group_list = $this->Application->ConfigValue('User_GuestGroup') . ',' . $this->Application->ConfigValue('User_LoggedInGroup');
$this->Application->StoreVar('UserGroups', $group_list, true);
$this->Application->Session->SetField('GroupList', $group_list);
if ($this->Application->ConfigValue('UseJSRedirect')) {
$this->event->SetRedirectParam('js_redirect', 1);
}
$this->Application->resetCounters('UserSessions');
$this->Application->Session->SetCookie('remember_login', '', strtotime('-1 hour'));
// don't pass user prefix on logout, since resulting url will have broken "env"
$this->event->SetRedirectParam('pass', MOD_REWRITE ? 'm' : 'all');
$this->_fixNextTemplate();
}
/**
* Returns user id based on given criteria
*
* @param string $username
* @param string $password
* @param string $remember_login_cookie
* @return int
*/
function getUserId($username, $password, $remember_login_cookie)
{
if ( $remember_login_cookie ) {
list ($username, $password) = explode('|', $remember_login_cookie); // 0 - username, 1 - md5(password_hash)
}
$sql = 'SELECT PortalUserId, Password, PasswordHashingMethod
FROM ' . TABLE_PREFIX . 'Users
WHERE ' . (strpos($username, '@') === false ? 'Username' : 'Email') . ' = %1$s';
$user_info = $this->Conn->GetRow(sprintf($sql, $this->Conn->qstr($username)));
if ( $user_info ) {
if ( $remember_login_cookie ) {
return md5($user_info['Password']) == $password ? $user_info['PortalUserId'] : false;
}
else {
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
$hashing_method = $user_info['PasswordHashingMethod'];
if ( $password_formatter->checkPassword($password, $user_info['Password'], $hashing_method) ) {
if ( $hashing_method != PasswordHashingMethod::PHPPASS ) {
$this->_fixUserPassword($user_info['PortalUserId'], $password);
}
return $user_info['PortalUserId'];
}
}
}
return false;
}
/**
* Apply new password hashing to given user's password
*
* @param int $user_id
* @param string $password
* @return void
* @access protected
*/
protected function _fixUserPassword($user_id, $password)
{
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
$fields_hash = Array (
'Password' => $password_formatter->hashPassword($password),
'PasswordHashingMethod' => PasswordHashingMethod::PHPPASS,
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Users', 'PortalUserId = ' . $user_id);
}
/**
* Process all required data and redirect logged-in user
*
* @param string $username
* @param string $password
* @return void
*/
protected function _processLoginRedirect($username = null, $password = null)
{
// set next template
$next_template = $this->Application->GetVar('next_template');
if ( $next_template ) {
$this->event->redirect = $next_template;
}
// process IIS redirect
if ( $this->Application->ConfigValue('UseJSRedirect') ) {
$this->event->SetRedirectParam('js_redirect', 1);
}
// synchronize login
/** @var UsersSyncronizeManager $sync_manager */
$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array (), Array ('InPortalSyncronize'));
if ( isset($username) && isset($password) ) {
$sync_manager->performAction('LoginUser', $username, $password);
}
else {
$sync_manager->performAction('LogoutUser');
}
}
/**
* Sets correct interface language after successful login, based on user settings
*
* @return void
* @access protected
*/
protected function _processInterfaceLanguage()
{
if ( defined('IS_INSTALL') && IS_INSTALL ) {
$this->event->SetRedirectParam('m_lang', 1); // data
$this->Application->Session->SetField('Language', 1); // interface
return;
}
$language_field = $this->Application->isAdmin ? 'AdminLanguage' : 'FrontLanguage';
$primary_language_field = $this->Application->isAdmin ? 'AdminInterfaceLang' : 'PrimaryLang';
$is_root = $this->Application->RecallVar('user_id') == USER_ROOT;
$object =& $this->getUserObject();
$user_language_id = $is_root ? $this->Application->RecallPersistentVar($language_field) : $object->GetDBField($language_field);
$sql = 'SELECT LanguageId, IF(LanguageId = ' . (int)$user_language_id . ', 2, ' . $primary_language_field . ') AS SortKey
FROM ' . TABLE_PREFIX . 'Languages
WHERE Enabled = 1
HAVING SortKey <> 0
ORDER BY SortKey DESC';
$language_info = $this->Conn->GetRow($sql);
$language_id = $language_info && $language_info['LanguageId'] ? $language_info['LanguageId'] : $user_language_id;
if ( $user_language_id != $language_id ) {
// first login OR language was deleted or disabled
if ( $is_root ) {
$this->Application->StorePersistentVar($language_field, $language_id);
}
else {
$object->SetDBField($language_field, $language_id);
$object->Update();
}
}
// set language for Admin Console & Front-End with disabled Mod-Rewrite
$this->event->SetRedirectParam('m_lang', $language_id); // data
$this->Application->Session->SetField('Language', $language_id); // interface
}
/**
* Injects redirect params into next template, which doesn't happen if next template starts with "external:"
*
* @return void
* @access protected
*/
protected function _fixNextTemplate()
{
if ( !MOD_REWRITE || !is_object($this->event) ) {
return;
}
// solve problem, when template is "true" instead of actual template name
$template = is_string($this->event->redirect) ? $this->event->redirect : '';
$url = $this->Application->HREF($template, '', $this->event->getRedirectParams(), $this->event->redirectScript);
$vars = $this->Application->parseRewriteUrl($url, 'pass');
unset($vars['login'], $vars['logout']);
// merge back url params, because they were ignored if this was "external:" url
$vars = array_merge($vars, $this->getRedirectParams($vars['pass'], 'pass'));
if ( $template != 'index' ) {
// The 'index.html' becomes '', which in turn leads to current page instead of 'index.html'.
$template = $vars['t'];
}
unset($vars['is_virtual'], $vars['t']);
$this->event->redirect = $template;
$this->event->setRedirectParams($vars, false);
}
/**
* Returns current event redirect params with given $prefixes injected into 'pass'.
*
* @param array $prefixes List of prefixes to inject.
* @param string $pass_name Name of array key in redirect params, containing comma-separated prefixes list.
*
* @return string
* @access protected
*/
protected function getRedirectParams($prefixes, $pass_name = 'passed')
{
$redirect_params = $this->event->getRedirectParams();
if ( isset($redirect_params[$pass_name]) ) {
$redirect_prefixes = explode(',', $redirect_params[$pass_name]);
$prefixes = array_unique(array_merge($prefixes, $redirect_prefixes));
}
$redirect_params[$pass_name] = implode(',', $prefixes);
return $redirect_params;
}
/**
* Checks that user is allowed to use super admin mode
*
* @return bool
*/
function verifySuperAdmin()
{
$sa_mode = kUtil::ipMatch(defined('SA_IP') ? SA_IP : '');
return $sa_mode || $this->Application->isDebugMode();
}
/**
* Returns user object, used during login processing
*
* @return UsersItem
* @access public
*/
public function &getUserObject()
{
$prefix_special = $this->Application->isAdmin ? 'u.current' : 'u'; // "u" used on front not to change theme
/** @var UsersItem $object */
$object = $this->Application->recallObject($prefix_special, null, Array('skip_autoload' => true));
return $object;
}
/**
* Checks, if given user fields matches at least one of defined ban rules
*
* @param kDBItem $object
* @return bool
*/
function checkBanRules(&$object)
{
$table = $this->Application->getUnitOption('ban-rule', 'TableName');
if (!$this->Conn->TableFound($table)) {
// when ban table not found -> assume user is ok by default
return true;
}
$sql = 'SELECT *
FROM ' . $table . '
WHERE ItemType = 6 AND Status = ' . STATUS_ACTIVE . '
ORDER BY Priority DESC';
$rules = $this->Conn->Query($sql);
$found = false;
foreach ($rules as $rule) {
$field = $rule['ItemField'];
$this_value = mb_strtolower( $object->GetDBField($field) );
$test_value = mb_strtolower( $rule['ItemValue'] );
switch ( $rule['ItemVerb'] ) {
case 1: // is
if ($this_value == $test_value) {
$found = true;
}
break;
case 2: // is not
if ($this_value != $test_value) {
$found = true;
}
break;
case 3: // contains
if ( strstr($this_value, $test_value) ) {
$found = true;
}
break;
case 4: // not contains
if ( !strstr($this_value, $test_value) ) {
$found = true;
}
break;
case 7: // exists
if ( strlen($this_value) > 0 ) {
$found = true;
}
break;
case 8: // unique
if ( $this->_checkValueExist($field, $this_value) ) {
$found = true;
}
break;
}
if ( $found ) {
// check ban rules, until one of them matches
if ( $rule['RuleType'] ) {
// invert rule type
$found = false;
}
break;
}
}
return !$found;
}
/**
* Checks if value is unique in Users table against the specified field
*
* @param string $field
* @param string $value
* @return string
*/
function _checkValueExist($field, $value)
{
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('u', 'TableName') . '
WHERE '. $field .' = ' . $this->Conn->qstr($value);
return $this->Conn->GetOne($sql);
}
public function validateUserCode($user_code, $code_type, $expiration_timeout = null)
{
$expiration_timeouts = Array (
'forgot_password' => 'config:Users_AllowReset',
'activation' => 'config:UserEmailActivationTimeout',
'verify_email' => 'config:Users_AllowReset',
'custom' => '',
);
if ( !$user_code ) {
return 'code_is_not_valid';
}
$sql = 'SELECT PwRequestTime, PortalUserId
FROM ' . TABLE_PREFIX . 'Users
WHERE PwResetConfirm = ' . $this->Conn->qstr( trim($user_code) );
$user_info = $this->Conn->GetRow($sql);
if ( $user_info === false ) {
return 'code_is_not_valid';
}
$expiration_timeout = isset($expiration_timeout) ? $expiration_timeout : $expiration_timeouts[$code_type];
if ( preg_match('/^config:(.*)$/', $expiration_timeout, $regs) ) {
$expiration_timeout = $this->Application->ConfigValue( $regs[1] );
}
if ( $expiration_timeout && $user_info['PwRequestTime'] < strtotime('-' . $expiration_timeout . ' minutes') ) {
return 'code_expired';
}
return $user_info['PortalUserId'];
}
/**
* Restores user's email, returns error label, if error occurred
*
* @param string $hash
* @return string
* @access public
*/
public function restoreEmail($hash)
{
if ( !preg_match('/^[a-f0-9]{32}$/', $hash) ) {
return 'invalid_hash';
}
$sql = 'SELECT PortalUserId, PrevEmails
FROM ' . TABLE_PREFIX . 'Users
WHERE PrevEmails LIKE ' . $this->Conn->qstr('%' . $hash . '%');
$user_info = $this->Conn->GetRow($sql);
if ( $user_info === false ) {
return 'invalid_hash';
}
$prev_emails = $user_info['PrevEmails'];
$prev_emails = $prev_emails ? unserialize($prev_emails) : Array ();
if ( !isset($prev_emails[$hash]) ) {
return 'invalid_hash';
}
$email_to_restore = $prev_emails[$hash];
unset($prev_emails[$hash]);
/** @var UsersItem $object */
$object = $this->Application->recallObject('u.email-restore', null, Array ('skip_autoload' => true));
$object->Load($user_info['PortalUserId']);
$object->SetDBField('PrevEmails', serialize($prev_emails));
$object->SetDBField('Email', $email_to_restore);
$object->SetDBField('EmailVerified', 1);
return $object->Update() ? '' : 'restore_impossible';
}
/**
* Returns user's primary group.
*
* @param integer $user_id User ID.
*
* @return integer
*/
public function getPrimaryGroup($user_id)
{
if ( $user_id <= 0 ) {
return $this->Application->ConfigValue('User_LoggedInGroup');
}
$cache_key = 'user' . $user_id . '_primary_group[%UIDSerial:' . $user_id . '%]';
$cache_value = $this->Application->getCache($cache_key);
if ( $cache_value === false ) {
$sql = 'SELECT PrimaryGroupId
FROM ' . TABLE_PREFIX . 'Users
WHERE PortalUserId = ' . $user_id;
$cache_value = $this->Conn->GetOne($sql);
$this->Application->setCache($cache_key, $cache_value);
}
return $cache_value;
}
}
Index: branches/5.2.x/core/units/phrases/phrases_event_handler.php
===================================================================
--- branches/5.2.x/core/units/phrases/phrases_event_handler.php (revision 16803)
+++ branches/5.2.x/core/units/phrases/phrases_event_handler.php (revision 16804)
@@ -1,550 +1,550 @@
<?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 PhrasesEventHandler extends kDBEventHandler
{
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnItemBuild' => Array ('self' => true, 'subitem' => true),
'OnPreparePhrase' => Array ('self' => true, 'subitem' => true),
'OnExportPhrases' => Array ('self' => 'view'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Hides phrases from disabled modules
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
/** @var kDBList $object */
$object = $event->getObject();
$object->addFilter('module_filter', '%1$s.Module IN (SELECT Name FROM ' . TABLE_PREFIX . 'Modules WHERE Loaded = 1)');
}
/**
* Apply some special processing to object being
* recalled before using it in other events that
* call prepareObject
*
* @param kDBItem|kDBList $object
* @param kEvent $event
* @return void
* @access protected
*/
protected function prepareObject(&$object, kEvent $event)
{
// don't call parent
if ( $event->Special == 'import' || $event->Special == 'export' ) {
$this->RemoveRequiredFields($object);
$object->setRequired(Array ('ExportDataTypes', 'LangFile', 'PhraseType', 'Module'));
// allow multiple phrase types to be selected during import/export
$object->SetFieldOption('PhraseType', 'type', 'string');
}
}
/**
* Allow to create phrases from front end in debug mode with DBG_PHRASES constant set
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
if ( !$this->Application->isAdmin && $this->Application->isDebugMode(false) && kUtil::constOn('DBG_PHRASES') ) {
$allow_events = Array ('OnCreate', 'OnCreateAjax', 'OnUpdate', 'OnUpdateAjax');
if ( in_array($event->Name, $allow_events) ) {
return true;
}
}
return parent::CheckPermission($event);
}
/**
* Prepares phrase for translation
*
* @param kEvent $event
*/
function OnPreparePhrase($event)
{
$label = $this->Application->GetVar($event->getPrefixSpecial() . '_label');
if (!$label) {
return ;
}
// we got label, try to get it's ID then if any
$phrase_id = $this->_getPhraseId($label);
if ($phrase_id) {
$event->SetRedirectParam($event->getPrefixSpecial(true) . '_id', $phrase_id);
$event->SetRedirectParam('pass', 'm,' . $event->getPrefixSpecial());
$next_template = $this->Application->GetVar('next_template');
if ($next_template) {
$event->SetRedirectParam('next_template', $next_template);
}
}
else {
$event->CallSubEvent('OnNew');
}
if ($this->Application->GetVar('simple_mode')) {
$event->SetRedirectParam('simple_mode', 1);
}
}
function _getPhraseId($phrase)
{
$sql = 'SELECT ' . $this->Application->getUnitOption($this->Prefix, 'IDField') . '
FROM ' . $this->Application->getUnitOption($this->Prefix, 'TableName') . '
WHERE PhraseKey = ' . $this->Conn->qstr( mb_strtoupper($phrase) );
return $this->Conn->GetOne($sql);
}
/**
* Sets phrase type based on place where it's created (to display on form only)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreCreate(kEvent $event)
{
parent::OnPreCreate($event);
/** @var kDBItem $object */
$object = $event->getObject();
$this->_setPhraseModule($object);
}
/**
* Forces new label in case if issued from get link
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnNew(kEvent $event)
{
parent::OnNew($event);
/** @var kDBItem $object */
$object = $event->getObject();
$label = $this->Application->GetVar($event->getPrefixSpecial() . '_label');
if ( $label ) {
// phrase is created in language, used to display phrases
$object->SetDBField('Phrase', $label);
$object->SetDBField('PhraseType', $this->_getPhraseType($label)); // to show on form
$object->SetDBField('PrimaryTranslation', $this->_getPrimaryTranslation($label));
}
$this->_setPhraseModule($object);
if ( $event->Special == 'export' || $event->Special == 'import' ) {
$object->SetDBField('PhraseType', '|0|1|2|');
$object->SetDBField('Module', '|' . implode('|', array_keys($this->Application->ModuleInfo)) . '|');
$export_mode = $this->Application->GetVar('export_mode');
if ( $export_mode != 'lang' ) {
$object->SetDBField('ExportDataTypes', '|' . $export_mode . '|');
}
}
}
/**
* Returns given phrase translation on primary language
*
* @param string $phrase
* @return string
* @access protected
*/
protected function _getPrimaryTranslation($phrase)
{
$sql = 'SELECT l' . $this->Application->GetDefaultLanguageId() . '_Translation
FROM ' . $this->Application->getUnitOption($this->Prefix, 'TableName') . '
WHERE PhraseKey = ' . $this->Conn->qstr( mb_strtoupper($phrase) );
return $this->Conn->GetOne($sql);
}
/**
* Sets new phrase module
*
* @param kDBItem $object
* @return void
* @access protected
*/
protected function _setPhraseModule(&$object)
{
- $last_module = $this->Application->GetVar('last_module');
+ $last_module = $this->Application->GetVarDirect('last_module', 'Cookie');
if ( $last_module ) {
$object->SetDBField('Module', $last_module);
}
}
/**
* Forces create to use live table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCreate(kEvent $event)
{
if ( $this->Application->GetVar($event->Prefix . '_label') ) {
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
if ( $this->Application->GetVar('m_lang') != $this->Application->GetVar('lang_id') ) {
$object->SwitchToLive();
}
$this->returnToOriginalTemplate($event);
}
parent::OnCreate($event);
}
/**
* Processes items create from ajax request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCreateAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnCreate');
}
/**
* Redirects to original template after phrase is being update
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdate(kEvent $event)
{
if ( $this->Application->GetVar($event->Prefix . '_label') ) {
$this->returnToOriginalTemplate($event);
}
parent::OnUpdate($event);
}
/**
* Processes items update from ajax request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdateAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnUpdate');
}
/**
* Returns to original template after phrase adding/editing
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function returnToOriginalTemplate(kEvent $event)
{
$next_template = $this->Application->GetVar('next_template');
if ( $next_template ) {
$event->redirect = $next_template;
$event->SetRedirectParam('opener', 's');
}
}
/**
* Set last change info, when phrase is created
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
/** @var kDBItem $object */
$object = $event->getObject();
$primary_language_id = $this->Application->GetDefaultLanguageId();
if ( !$object->GetDBField('l' . $primary_language_id . '_Translation') ) {
// no translation on primary language -> try to copy from other language
$src_languages = Array ('lang_id', 'm_lang'); // editable language, theme language
foreach ($src_languages as $src_language) {
$src_language = $this->Application->GetVar($src_language);
$src_value = $src_language ? $object->GetDBField('l' . $src_language . '_Translation') : false;
if ( $src_value ) {
$object->SetDBField('l' . $primary_language_id . '_Translation', $src_value);
break;
}
}
}
$this->_phraseChanged($event);
}
/**
* Update last change info, when phrase is updated
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->_phraseChanged($event);
}
/**
* Set's phrase key and last change info, used for phrase updating and loading
*
* @param kEvent $event
*/
function _phraseChanged($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$label = $object->GetDBField('Phrase');
$object->SetDBField('PhraseKey', mb_strtoupper($label));
$object->SetDBField('PhraseType', $this->_getPhraseType($label));
if ( $this->translationChanged($object) ) {
$object->SetDBField('LastChanged_date', adodb_mktime() );
$object->SetDBField('LastChanged_time', adodb_mktime() );
$object->SetDBField('LastChangeIP', $this->Application->getClientIp());
}
$this->Application->Session->SetCookie('last_module', $object->GetDBField('Module'));
}
/**
* Returns phrase type, that corresponds given phrase label
*
* @param string $label
* @return int
* @access protected
*/
protected function _getPhraseType($label)
{
$phrase_type_map = Array (
'LU' => Language::PHRASE_TYPE_FRONT,
'LA' => Language::PHRASE_TYPE_ADMIN,
'LC' => Language::PHRASE_TYPE_COMMON
);
$label = mb_strtoupper($label);
$label_prefix = substr($label, 0, 2);
return isset($phrase_type_map[$label_prefix]) ? $phrase_type_map[$label_prefix] : Language::PHRASE_TYPE_COMMON;
}
/**
* Checks, that at least one of phrase's translations was changed
*
* @param kDBItem $object
* @return bool
*/
function translationChanged(&$object)
{
$changed_fields = array_keys( $object->GetChangedFields() );
$translation_fields = Array ('Translation', 'HintTranslation', 'ColumnTranslation');
foreach ($changed_fields as $changed_field) {
$changed_field = preg_replace('/^l[\d]+_/', '', $changed_field);
if ( in_array($changed_field, $translation_fields) ) {
return true;
}
}
return false;
}
/**
* Changes default module to custom (when available)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
if ($this->Application->findModule('Name', 'Custom')) {
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$fields['Module']['default'] = 'Custom';
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
// make sure, that PrimaryTranslation column always refrers to primary language column
$language_id = $this->Application->GetVar('lang_id');
if (!$language_id) {
$language_id = $this->Application->GetVar('m_lang');
}
$primary_language_id = $this->Application->GetDefaultLanguageId();
$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
foreach ($calculated_fields[''] as $field_name => $field_expression) {
$field_expression = str_replace('%5$s', $language_id, $field_expression);
$field_expression = str_replace('%4$s', $primary_language_id, $field_expression);
$calculated_fields[''][$field_name] = $field_expression;
}
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
if ($this->Application->GetVar('regional')) {
$this->Application->setUnitOption($event->Prefix, 'PopulateMlFields', true);
}
}
/**
* Saves changes & changes language
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveAndChangeLanguage(kEvent $event)
{
$label = $this->Application->GetVar($event->getPrefixSpecial() . '_label');
if ( $label && !$this->UseTempTables($event) ) {
$phrase_id = $this->_getPhraseId($label);
if ( $phrase_id ) {
$event->CallSubEvent('OnUpdate');
$event->SetRedirectParam('opener', 's');
}
else {
$event->CallSubEvent('OnCreate');
$event->SetRedirectParam('opener', 's');
}
if ( $event->status != kEvent::erSUCCESS ) {
return;
}
$event->SetRedirectParam($event->getPrefixSpecial() . '_event', 'OnPreparePhrase');
$event->SetRedirectParam('pass_events', true);
}
if ( $this->Application->GetVar('simple_mode') ) {
$event->SetRedirectParam('simple_mode', 1);
}
parent::OnPreSaveAndChangeLanguage($event);
}
/**
* Prepare temp tables and populate it
* with items selected in the grid
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnEdit(kEvent $event)
{
parent::OnEdit($event);
// use language from grid, instead of primary language used by default
$event->SetRedirectParam('m_lang', $this->Application->GetVar('m_lang'));
}
/**
* Stores ids of selected phrases and redirects to export language step 1
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnExportPhrases(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
$this->Application->setUnitOption('phrases', 'AutoLoad', false);
$this->StoreSelectedIDs($event);
$this->Application->StoreVar('export_language_ids', $this->Application->GetVar('m_lang'));
$event->setRedirectParams(
Array (
'phrases.export_event' => 'OnNew',
'pass' => 'all,phrases.export',
'export_mode' => $event->Prefix,
)
);
}
}
Index: branches/5.2.x/core/units/users/users_event_handler.php
===================================================================
--- branches/5.2.x/core/units/users/users_event_handler.php (revision 16803)
+++ branches/5.2.x/core/units/users/users_event_handler.php (revision 16804)
@@ -1,1952 +1,1952 @@
<?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 UsersEventHandler extends kDBEventHandler
{
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
// admin
'OnSetPersistantVariable' => Array('self' => 'view'), // because setting to logged in user only
'OnUpdatePassword' => Array('self' => true),
'OnSaveSelected' => Array ('self' => 'view'),
'OnGeneratePassword' => Array ('self' => 'view'),
// front
'OnRefreshForm' => Array('self' => true),
'OnForgotPassword' => Array('self' => true),
'OnSubscribeQuery' => Array('self' => true),
'OnSubscribeUser' => Array('self' => true),
'OnRecommend' => Array('self' => true),
'OnItemBuild' => Array('self' => true),
'OnMassResetSettings' => Array('self' => 'edit'),
'OnMassCloneUsers' => Array('self' => 'add'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Builds item (loads if needed)
*
* Pattern: Prototype Manager
*
* @param kEvent $event
* @access protected
*/
protected function OnItemBuild(kEvent $event)
{
parent::OnItemBuild($event);
/** @var kDBItem $object */
$object = $event->getObject();
if ( $event->Special == 'forgot' || $object->getFormName() == 'registration' ) {
$this->_makePasswordRequired($event);
}
}
/**
* Shows only admins when required
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
/** @var kDBList $object */
$object = $event->getObject();
if ( $event->Special == 'regular' ) {
$object->addFilter('primary_filter', '%1$s.UserType = ' . UserType::USER);
}
if ( $event->Special == 'admins' ) {
$object->addFilter('primary_filter', '%1$s.UserType = ' . UserType::ADMIN);
}
if ( !$this->Application->isAdminUser ) {
$object->addFilter('status_filter', '%1$s.Status = ' . STATUS_ACTIVE);
}
if ( $event->Special == 'online' ) {
$object->addFilter('online_users_filter', 's.PortalUserId IS NOT NULL');
}
if ( $event->Special == 'group' ) {
$group_id = $this->Application->GetVar('g_id');
if ( $group_id !== false ) {
// show only users, that user doesn't belong to current group
$sql = 'SELECT PortalUserId
FROM ' . $this->Application->GetTempName(TABLE_PREFIX . 'UserGroupRelations', 'prefix:g') . '
WHERE GroupId = ' . (int)$group_id;
$user_ids = $this->Conn->GetCol($sql);
if ( $user_ids ) {
$object->addFilter('already_member_filter', '%1$s.PortalUserId NOT IN (' . implode(',', $user_ids) . ')');
}
}
}
}
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
if ( $event->Name == 'OnLogin' || $event->Name == 'OnLoginAjax' || $event->Name == 'OnLogout' ) {
// permission is checked in OnLogin event directly
return true;
}
if ( $event->Name == 'OnResetRootPassword' ) {
return defined('DBG_RESET_ROOT') && DBG_RESET_ROOT;
}
if ( $event->Name == 'OnLoginAs' ) {
/** @var Session $admin_session */
$admin_session = $this->Application->recallObject('Session.admin');
return $admin_session->LoggedIn();
}
if ( !$this->Application->isAdminUser ) {
$user_id = $this->Application->RecallVar('user_id');
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( ($event->Name == 'OnCreate' || $event->Name == 'OnRegisterAjax') && $user_id == USER_GUEST ) {
// "Guest" can create new users
return true;
}
if ( substr($event->Name, 0, 8) == 'OnUpdate' && $user_id > 0 ) {
/** @var UsersItem $user_dummy */
$user_dummy = $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true));
foreach ($items_info as $id => $field_values) {
if ( $id != $user_id ) {
// registered users can update their record only
return false;
}
$user_dummy->Load($id);
$status_field = $user_dummy->getStatusField();
if ( $user_dummy->GetDBField($status_field) != STATUS_ACTIVE ) {
// not active user is not allowed to update his record (he could not activate himself manually)
return false;
}
if ( isset($field_values[$status_field]) && $user_dummy->GetDBField($status_field) != $field_values[$status_field] ) {
// user can't change status by himself
return false;
}
}
return true;
}
if ( $event->Name == 'OnResetLostPassword' && $event->Special == 'forgot' && $user_id == USER_GUEST ) {
// non-logged in users can reset their password, when reset code is valid
return is_numeric($this->getPassedID($event));
}
if ( substr($event->Name, 0, 8) == 'OnUpdate' && $user_id <= 0 ) {
// guests are not allowed to update their record, because they don't have it :)
return false;
}
}
return parent::CheckPermission($event);
}
/**
* Handles session expiration (redirects to valid template)
*
* @param kEvent $event
*/
function OnSessionExpire($event)
{
$this->Application->resetCounters('UserSessions');
// place 2 of 2 (also in kHTTPQuery::getRedirectParams)
$admin_url_params = Array (
'm_cat_id' => 0, // category means nothing on admin login screen
'm_wid' => '', // remove wid, otherwise parent window may add wid to its name breaking all the frameset (for <a> targets)
'pass' => 'm', // don't pass any other (except "m") prefixes to admin session expiration template
'expired' => 1, // expiration mark to show special error on login screen
'no_pass_through' => 1, // this way kApplication::HREF won't add them again
);
if ($this->Application->isAdmin) {
$this->Application->Redirect('index', $admin_url_params, '', 'index.php');
}
if ($this->Application->GetVar('admin') == 1) {
// Front-End showed in admin's right frame
/** @var Session $session_admin */
$session_admin = $this->Application->recallObject('Session.admin');
if (!$session_admin->LoggedIn()) {
// front-end session created from admin session & both expired
$this->Application->DeleteVar('admin');
$this->Application->Redirect('index', $admin_url_params, '', 'admin/index.php');
}
}
// Front-End session expiration
$get = $this->Application->HttpQuery->getRedirectParams();
$t = $this->Application->GetVar('t');
$get['js_redirect'] = $this->Application->ConfigValue('UseJSRedirect');
$this->Application->Redirect($t ? $t : 'index', $get);
}
/**
* [SCHEDULED TASK] Deletes expired sessions
*
* @param kEvent $event
*/
function OnDeleteExpiredSessions($event)
{
if (defined('IS_INSTALL') && IS_INSTALL) {
return ;
}
/** @var SessionStorage $session_storage */
$session_storage = $this->Application->recallObject('SessionStorage');
$session_storage->DeleteExpired();
}
/**
* Checks user data and logs it in if allowed
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLogin($event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('form_name' => 'login') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
$username = $object->GetDBField('UserLogin');
$password = $object->GetDBField('UserPassword');
$remember_login = $object->GetDBField('UserRememberLogin') == 1;
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->event =& $event;
$result = $user_helper->loginUser($username, $password, false, $remember_login);
if ($result != LoginResult::OK) {
$event->status = kEvent::erFAIL;
$object->SetError('UserLogin', $result == LoginResult::NO_PERMISSION ? 'no_permission' : 'invalid_password');
}
if ( is_object($event->MasterEvent) && ($event->MasterEvent->Name == 'OnLoginAjax') ) {
// used to insert just logged-in user e-mail on "One Step Checkout" form in "Modern Store" theme
$user =& $user_helper->getUserObject();
$event->SetRedirectParam('user_email', $user->GetDBField('Email'));
}
}
/**
* Performs user login from ajax request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLoginAjax($event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnLogin');
}
/**
* [HOOK] Auto-Logins Front-End user when "Remember Login" cookie is found
*
* @param kEvent $event
*/
function OnAutoLoginUser($event)
{
- $remember_login_cookie = $this->Application->GetVar('remember_login');
+ $remember_login_cookie = $this->Application->GetVarDirect('remember_login', 'Cookie');
if (!$remember_login_cookie || $this->Application->isAdmin || $this->Application->LoggedIn()) {
return ;
}
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->loginUser('', '', false, false, $remember_login_cookie);
}
/**
* Called when user logs in using old in-portal
*
* @param kEvent $event
*/
function OnInpLogin($event)
{
/** @var UsersSyncronizeManager $sync_manager */
$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array(), Array ('InPortalSyncronize'));
$sync_manager->performAction('LoginUser', $event->getEventParam('user'), $event->getEventParam('pass') );
if ($event->redirect && is_string($event->redirect)) {
// some real template specified instead of true
$this->Application->Redirect($event->redirect, $event->getRedirectParams());
}
}
/**
* Called when user logs in using old in-portal
*
* @param kEvent $event
*/
function OnInpLogout($event)
{
/** @var UsersSyncronizeManager $sync_manager */
$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array(), Array ('InPortalSyncronize'));
$sync_manager->performAction('LogoutUser');
}
/**
* Performs user logout
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLogout($event)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->event =& $event;
$user_helper->logoutUser();
}
/**
* Redirects user after successful registration to confirmation template (on Front only)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemCreate(kEvent $event)
{
parent::OnAfterItemCreate($event);
$this->afterItemChanged($event);
$this->assignToPrimaryGroup($event);
}
/**
* Performs user registration
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCreate(kEvent $event)
{
if ( $this->Application->isAdmin ) {
parent::OnCreate($event);
return ;
}
/** @var UsersItem $object */
$object = $event->getObject( Array('form_name' => 'registration') );
$field_values = $this->getSubmittedFields($event);
$user_email = getArrayValue($field_values, 'Email');
$subscriber_id = $user_email ? $this->getSubscriberByEmail($user_email) : false;
if ( $subscriber_id ) {
// update existing subscriber
$object->Load($subscriber_id);
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_NewGroup'));
$this->Application->SetVar($event->getPrefixSpecial(true), Array ($object->GetID() => $field_values));
}
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$status = $object->isLoaded() ? $object->Update() : $object->Create();
if ( !$status ) {
$event->status = kEvent::erFAIL;
$event->redirect = false;
$object->setID( (int)$object->GetID() );
}
$this->setNextTemplate($event, true);
if ( ($event->status == kEvent::erSUCCESS) && $event->redirect ) {
$this->assignToPrimaryGroup($event);
$object->sendEmails();
$this->autoLoginUser($event);
}
}
/**
* Processes user registration from ajax request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRegisterAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnCreate', Array ('do_refresh' => 1));
}
/**
* Returns subscribed user ID by given e-mail address
*
* @param string $email
* @return int|bool
* @access protected
*/
protected function getSubscriberByEmail($email)
{
/** @var UsersItem $verify_user */
$verify_user = $this->Application->recallObject('u.verify', null, Array ('skip_autoload' => true));
$verify_user->Load($email, 'Email');
return $verify_user->isLoaded() && $verify_user->isSubscriberOnly() ? $verify_user->GetID() : false;
}
/**
* Login user if possible, if not then redirect to corresponding template
*
* @param kEvent $event
*/
function autoLoginUser($event)
{
/** @var UsersItem $object */
$object = $event->getObject();
if ( $object->GetDBField('Status') == STATUS_ACTIVE ) {
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user =& $user_helper->getUserObject();
$user->Load($object->GetID());
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
/**
* Set's new unique resource id to user
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->beforeItemChanged($event);
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
/** @var UsersItem $object */
$object = $event->getObject();
if ( !$object->isSubscriberOnly() ) {
// don't check state-to-country relations for subscribers
$cs_helper->CheckStateField($event, 'State', 'Country');
}
if ( $object->getFormName() != 'login' ) {
$this->_makePasswordRequired($event);
}
$cs_helper->PopulateStates($event, 'State', 'Country');
$this->setUserGroup($object);
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
if ( !$user_helper->checkBanRules($object) ) {
$object->SetError('Username', 'banned');
}
$object->SetDBField('IPAddress', $this->Application->getClientIp());
if ( !$this->Application->isAdmin ) {
$object->SetDBField('FrontLanguage', $this->Application->GetVar('m_lang'));
}
}
/**
* Sets primary group of the user
*
* @param kDBItem $object
*/
protected function setUserGroup(&$object)
{
if ($object->Special == 'subscriber') {
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_SubscriberGroup'));
return ;
}
// set primary group to user
if ( !$this->Application->isAdminUser ) {
$group_id = $object->GetDBField('PrimaryGroupId');
if ($group_id) {
// check, that group is allowed for Front-End
$sql = 'SELECT GroupId
FROM ' . TABLE_PREFIX . 'UserGroups
WHERE GroupId = ' . (int)$group_id . ' AND FrontRegistration = 1';
$group_id = $this->Conn->GetOne($sql);
}
if (!$group_id) {
// when group not selected OR not allowed -> use default group
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_NewGroup'));
}
}
}
/**
* Assigns a user to it's primary group
*
* @param kEvent $event
*/
protected function assignToPrimaryGroup($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$primary_group_id = $object->GetDBField('PrimaryGroupId');
if ($primary_group_id) {
$ug_table = TABLE_PREFIX . 'UserGroupRelations';
if ( $object->IsTempTable() ) {
$ug_table = $this->Application->GetTempName($ug_table, 'prefix:' . $event->Prefix);
}
$fields_hash = Array (
'PortalUserId' => $object->GetID(),
'GroupId' => $primary_group_id,
);
$this->Conn->doInsert($fields_hash, $ug_table, 'REPLACE');
}
}
/**
* Set's new unique resource id to user
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemValidate(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$resource_id = $object->GetDBField('ResourceId');
if ( !$resource_id ) {
$object->SetDBField('ResourceId', $this->Application->NextResourceId());
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnRecommend($event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('form_name' => 'recommend') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
if ( !$object->ValidateField('RecommendEmail') ) {
$event->status = kEvent::erFAIL;
return ;
}
$send_params = Array (
'to_email' => $object->GetDBField('RecommendEmail'),
'to_name' => $object->GetDBField('RecommendEmail'),
);
$user_id = $this->Application->RecallVar('user_id');
$email_sent = $this->Application->emailUser('USER.SUGGEST', $user_id, $send_params);
$this->Application->emailAdmin('USER.SUGGEST');
if ( $email_sent ) {
$event->SetRedirectParam('pass', 'all');
$event->redirect = $this->Application->GetVar('template_success');
}
else {
$event->status = kEvent::erFAIL;
$object->SetError('RecommendEmail', 'send_error');
}
}
/**
* Saves address changes and mades no redirect
*
* @param kEvent $event
*/
function OnUpdateAddress($event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( $items_info ) {
$id = key($items_info);
$field_values = $items_info[$id];
if ( $id > 0 ) {
$object->Load($id);
}
$object->setID($id);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$object->Validate();
}
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
$cs_helper->PopulateStates($event, 'State', 'Country');
$event->redirect = false;
}
/**
* Validate subscriber's email & store it to session -> redirect to confirmation template
*
* @param kEvent $event
*/
function OnSubscribeQuery($event)
{
/** @var UsersItem $object */
$object = $event->getObject( Array ('form_name' => 'subscription') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
if ( !$object->ValidateField('SubscriberEmail') ) {
$event->status = kEvent::erFAIL;
return ;
}
$user_email = $object->GetDBField('SubscriberEmail');
$object->Load($user_email, 'Email');
$event->SetRedirectParam('subscriber_email', $user_email);
if ( $object->isLoaded() && $object->isSubscribed() ) {
$event->redirect = $this->Application->GetVar('unsubscribe_template');
}
else {
$event->redirect = $this->Application->GetVar('subscribe_template');
}
$event->SetRedirectParam('pass', 'm');
}
/**
* Subscribe/Unsubscribe user based on email stored in previous step
*
* @param kEvent $event
*/
function OnSubscribeUser($event)
{
/** @var UsersItem $object */
$object = $event->getObject( Array ('form_name' => 'subscription') );
$user_email = $this->Application->GetVar('subscriber_email');
$object->SetDBField('SubscriberEmail', $user_email);
if ( !$object->ValidateField('SubscriberEmail') ) {
$event->status = kEvent::erFAIL;
return ;
}
$username_required = $object->isRequired('Username');
$this->RemoveRequiredFields($object);
$object->Load($user_email, 'Email');
if ( $object->isLoaded() ) {
if ( $object->isSubscribed() ) {
if ( $event->getEventParam('no_unsubscribe') ) {
// for customization code from FormsEventHandler
return ;
}
if ( $object->isSubscriberOnly() ) {
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->Prefix . '_TempHandler', 'kTempTablesHandler');
$temp_handler->DeleteItems($event->Prefix, '', Array($object->GetID()));
}
else {
$this->RemoveSubscriberGroup( $object->GetID() );
}
$event->redirect = $this->Application->GetVar('unsubscribe_ok_template');
}
else {
$this->AddSubscriberGroup($object);
$event->redirect = $this->Application->GetVar('subscribe_ok_template');
}
}
else {
$object->generatePassword();
$object->SetDBField('Email', $user_email);
if ( $username_required ) {
$object->SetDBField('Username', str_replace('@', '_at_', $user_email));
}
$object->SetDBField('Status', STATUS_ACTIVE); // make user subscriber Active by default
if ( $object->Create() ) {
$this->AddSubscriberGroup($object);
$event->redirect = $this->Application->GetVar('subscribe_ok_template');
}
}
}
/**
* Adding user to subscribers group
*
* @param UsersItem $object
*/
function AddSubscriberGroup(&$object)
{
if ( !$object->isSubscriberOnly() ) {
$fields_hash = Array (
'PortalUserId' => $object->GetID(),
'GroupId' => $this->Application->ConfigValue('User_SubscriberGroup'),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'UserGroupRelations');
}
$this->Application->emailAdmin('USER.SUBSCRIBE');
$this->Application->emailUser('USER.SUBSCRIBE', $object->GetID());
}
/**
* Removing user from subscribers group
*
* @param int $user_id
*/
function RemoveSubscriberGroup($user_id)
{
$group_id = $this->Application->ConfigValue('User_SubscriberGroup');
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'UserGroupRelations
WHERE PortalUserId = ' . $user_id . ' AND GroupId = ' . $group_id;
$this->Conn->Query($sql);
$this->Application->emailAdmin('USER.UNSUBSCRIBE');
$this->Application->emailUser('USER.UNSUBSCRIBE', $user_id);
}
/**
* Validates forgot password form and sends password reset confirmation e-mail
*
* @param kEvent $event
* @return void
*/
function OnForgotPassword($event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('form_name' => 'forgot_password') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
/** @var UsersItem $user */
$user = $this->Application->recallObject('u.tmp', null, Array ('skip_autoload' => true));
$found = $allow_reset = false;
$email_or_username = $object->GetDBField('ForgotLogin');
$is_email = strpos($email_or_username, '@') !== false;
if ( strlen($email_or_username) ) {
$user->Load($email_or_username, $is_email ? 'Email' : 'Username');
}
if ( $user->isLoaded() ) {
$min_pwd_reset_delay = $this->Application->ConfigValue('Users_AllowReset');
$found = ($user->GetDBField('Status') == STATUS_ACTIVE) && strlen($user->GetDBField('Password'));
if ( !$user->GetDBField('PwResetConfirm') ) {
// no reset made -> allow
$allow_reset = true;
}
else {
// reset made -> wait N minutes, then allow
$allow_reset = TIMENOW > $user->GetDBField('PwRequestTime') + $min_pwd_reset_delay;
}
}
if ( $found && $allow_reset ) {
$this->Application->emailUser('USER.PSWDC', $user->GetID());
$event->redirect = $this->Application->GetVar('template_success');
return;
}
if ( strlen($email_or_username) ) {
$object->SetError('ForgotLogin', $found ? 'reset_denied' : ($is_email ? 'unknown_email' : 'unknown_username'));
}
if ( !$object->ValidateField('ForgotLogin') ) {
$event->status = kEvent::erFAIL;
}
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdate(kEvent $event)
{
parent::OnUpdate($event);
if ( !$this->Application->isAdmin ) {
$this->setNextTemplate($event);
}
}
/**
* Updates kDBItem via AJAX.
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnUpdateAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnUpdate');
}
/**
* Checks state against country
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->beforeItemChanged($event);
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
$cs_helper->CheckStateField($event, 'State', 'Country');
$cs_helper->PopulateStates($event, 'State', 'Country');
/** @var kDBItem $object */
$object = $event->getObject();
if ( $event->Special == 'forgot' ) {
$object->SetDBField('PwResetConfirm', '');
$object->SetDBField('PwRequestTime_date', NULL);
$object->SetDBField('PwRequestTime_time', NULL);
}
$changed_fields = array_keys($object->GetChangedFields());
if ( $changed_fields && !in_array('Modified', $changed_fields) ) {
$object->SetDBField('Modified_date', adodb_mktime());
$object->SetDBField('Modified_time', adodb_mktime());
}
if ( !$this->Application->isAdmin && in_array('Email', $changed_fields) && ($event->Special != 'email-restore') ) {
$object->SetDBField('EmailVerified', 0);
}
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
function beforeItemChanged($event)
{
/** @var UsersItem $object */
$object = $event->getObject();
if ( !$this->Application->isAdmin && $object->getFormName() == 'registration' ) {
// sets new user's status based on config options
$status_map = Array (1 => STATUS_ACTIVE, 2 => STATUS_DISABLED, 3 => STATUS_PENDING, 4 => STATUS_PENDING);
$object->SetDBField('Status', $status_map[ $this->Application->ConfigValue('User_Allow_New') ]);
if ( $this->Application->ConfigValue('User_Password_Auto') ) {
$object->generatePassword( rand(5, 8) );
}
if ( $this->Application->ConfigValue('RegistrationCaptcha') ) {
/** @var kCaptchaHelper $captcha_helper */
$captcha_helper = $this->Application->recallObject('CaptchaHelper');
$captcha_helper->validateCode($event, false);
}
if ( $event->Name == 'OnBeforeItemUpdate' ) {
// when a subscriber-only users performs normal registration, then assign him to Member group
$this->setUserGroup($object);
}
}
}
/**
* Sets redirect template based on user status & user request contents
*
* @param kEvent $event
* @param bool $for_registration
*/
function setNextTemplate($event, $for_registration = false)
{
$event->SetRedirectParam('opener', 's');
/** @var UsersItem $object */
$object = $event->getObject();
$next_template = false;
if ( $object->GetDBField('Status') == STATUS_ACTIVE && $this->Application->GetVar('next_template') ) {
$next_template = $this->Application->GetVar('next_template');
}
elseif ( $for_registration ) {
switch ( $this->Application->ConfigValue('User_Allow_New') ) {
case 1: // Immediate
$next_template = $this->Application->GetVar('registration_confirm_template');
break;
case 3: // Upon Approval
case 4: // Email Activation
$next_template = $this->Application->GetVar('registration_confirm_pending_template');
break;
}
}
if ($next_template) {
$event->redirect = $next_template;
}
}
/**
* Delete users from groups if their membership is expired
*
* @param kEvent $event
*/
function OnCheckExpiredMembership($event)
{
// send pre-expiration reminders: begin
$pre_expiration = adodb_mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24;
$sql = 'SELECT PortalUserId, GroupId
FROM '.TABLE_PREFIX.'UserGroupRelations
WHERE (MembershipExpires IS NOT NULL) AND (ExpirationReminderSent = 0) AND (MembershipExpires < '.$pre_expiration.')';
$skip_clause = $event->getEventParam('skip_clause');
if ($skip_clause) {
$sql .= ' AND !('.implode(') AND !(', $skip_clause).')';
}
$records = $this->Conn->Query($sql);
if ($records) {
$conditions = Array();
foreach ($records as $record) {
$this->Application->emailUser('USER.MEMBERSHIP.EXPIRATION.NOTICE', $record['PortalUserId']);
$this->Application->emailAdmin('USER.MEMBERSHIP.EXPIRATION.NOTICE');
$conditions[] = '(PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'].')';
}
$sql = 'UPDATE '.TABLE_PREFIX.'UserGroupRelations
SET ExpirationReminderSent = 1
WHERE '.implode(' OR ', $conditions);
$this->Conn->Query($sql);
}
// send pre-expiration reminders: end
// remove users from groups with expired membership: begin
$sql = 'SELECT PortalUserId
FROM '.TABLE_PREFIX.'UserGroupRelations
WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')';
$user_ids = $this->Conn->GetCol($sql);
if ($user_ids) {
foreach ($user_ids as $id) {
$this->Application->emailUser('USER.MEMBERSHIP.EXPIRED', $id);
$this->Application->emailAdmin('USER.MEMBERSHIP.EXPIRED');
}
}
$sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroupRelations
WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')';
$this->Conn->Query($sql);
// remove users from groups with expired membership: end
}
/**
* Used to keep user registration form data, while showing affiliate registration form fields
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRefreshForm($event)
{
$event->redirect = false;
$item_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$id = key($item_info);
$field_values = $item_info[$id];
/** @var kDBItem $object */
$object = $event->getObject( Array ('skip_autoload' => true) );
$object->IgnoreValidation = true;
$object->setID($id);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
}
/**
* Sets persistant variable
*
* @param kEvent $event
*/
function OnSetPersistantVariable($event)
{
$field = $this->Application->GetVar('field');
$value = $this->Application->GetVar('value');
$this->Application->StorePersistentVar($field, $value);
$force_tab = $this->Application->GetVar('SetTab');
if ($force_tab) {
$this->Application->StoreVar('force_tab', $force_tab);
}
}
/**
* Return user from order by special .ord
*
* @param kEvent $event
* @return int
* @access public
*/
public function getPassedID(kEvent $event)
{
switch ($event->Special) {
case 'ord':
/** @var OrdersItem $order */
$order = $this->Application->recallObject('ord');
return $order->GetDBField('PortalUserId');
break;
case 'profile':
$id = $this->Application->GetVar('user_id');
if ( $id ) {
$event->setEventParam(kEvent::FLAG_ID_FROM_REQUEST, true);
return $id;
}
// If none user_id given use current user id.
return $this->Application->RecallVar('user_id');
break;
case 'forgot':
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$id = $user_helper->validateUserCode($this->Application->GetVar('user_key'), 'forgot_password');
if ( is_numeric($id) ) {
return $id;
}
break;
}
if ( preg_match('/^(login|register|recommend|subscribe|forgot)/', $event->Special) ) {
// this way we can have 2+ objects stating with same special, e.g. "u.login-sidebox" and "u.login-main"
return USER_GUEST;
}
elseif ( preg_match('/^(update|delete)/', $event->Special) ) {
// This way we can have 2+ objects stating with same special, e.g. "u.update-sidebox" and "u.update-profile".
return $this->Application->RecallVar('user_id');
}
return parent::getPassedID($event);
}
/**
* Allows to change root password
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdatePassword($event)
{
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
$id = key($items_info);
$field_values = $items_info[$id];
$user_id = $this->Application->RecallVar('user_id');
if ( $id == $user_id && ($user_id > 0 || $user_id == USER_ROOT) ) {
/** @var kDBItem $user_dummy */
$user_dummy = $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true));
$user_dummy->Load($id);
$status_field = $user_dummy->getStatusField();
if ( $user_dummy->GetDBField($status_field) != STATUS_ACTIVE ) {
// not active user is not allowed to update his record (he could not activate himself manually)
return ;
}
}
if ( $user_id == USER_ROOT ) {
/** @var UsersItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
// this is internal hack to allow root/root passwords for dev
if ( $this->Application->isDebugMode() && $field_values['RootPassword'] == 'root' ) {
$object->SetFieldOption('RootPassword', 'min_length', 4);
}
$this->RemoveRequiredFields($object);
$object->SetDBField('RootPassword', $this->Application->ConfigValue('RootPass'));
$object->setID(-1);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
if ( $object->Validate() ) {
// validation on, password match too
$fields_hash = Array ('VariableValue' => $object->GetDBField('RootPassword'));
$conf_table = $this->Application->getUnitOption('conf', 'TableName');
$this->Conn->doUpdate($fields_hash, $conf_table, 'VariableName = "RootPass"');
$event->SetRedirectParam('opener', 'u');
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
return ;
}
}
else {
/** @var kDBItem $object */
$object = $event->getObject();
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
if ( !$object->Update() ) {
$event->status = kEvent::erFAIL;
$event->redirect = false;
}
}
$event->SetRedirectParam('opener', 'u');
}
/**
* Resets grid settings, remembered in each user record
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMassResetSettings($event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
$ids = $this->StoreSelectedIDs($event);
$default_user_id = $this->Application->ConfigValue('DefaultSettingsUserId');
if ( in_array($default_user_id, $ids) ) {
array_splice($ids, array_search($default_user_id, $ids), 1);
}
if ( $ids ) {
$q = 'DELETE FROM ' . TABLE_PREFIX . 'UserPersistentSessionData WHERE PortalUserId IN (' . join(',', $ids) . ') AND
(VariableName LIKE "%_columns_%"
OR
VariableName LIKE "%_filter%"
OR
VariableName LIKE "%_PerPage%")';
$this->Conn->Query($q);
}
$this->clearSelectedIDs($event);
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
* @access protected
*/
protected function checkItemStatus(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
if ( !$object->isLoaded() ) {
return true;
}
$virtual_users = Array (USER_ROOT, USER_GUEST);
return ($object->GetDBField('Status') == STATUS_ACTIVE) || in_array($object->GetID(), $virtual_users);
}
/**
* Sends approved/declined email event on user status change
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
$this->afterItemChanged($event);
/** @var UsersItem $object */
$object = $event->getObject();
if ( !$this->Application->isAdmin && ($event->Special != 'email-restore') ) {
$this->sendEmailChangeEvent($event);
}
if ( !$this->Application->isAdmin || $object->IsTempTable() ) {
return;
}
$this->sendStatusChangeEvent($object->GetID(), $object->GetOriginalField('Status'), $object->GetDBField('Status'));
}
/**
* Occurs, after item is changed
*
* @param kEvent $event
*/
protected function afterItemChanged($event)
{
$this->saveUserImages($event);
/** @var UsersItem $object */
$object = $event->getObject();
if ( $object->GetDBField('EmailPassword') && $object->GetDBField('Password_plain') ) {
$email_passwords = $this->Application->RecallVar('email_passwords');
$email_passwords = $email_passwords ? unserialize($email_passwords) : Array ();
$email_passwords[ $object->GetID() ] = $object->GetDBField('Password_plain');
$this->Application->StoreVar('email_passwords', serialize($email_passwords));
}
// update user subscription status (via my profile or new user registration)
if ( !$this->Application->isAdmin && !$object->isSubscriberOnly() ) {
if ( $object->GetDBField('SubscribeToMailing') && !$object->isSubscribed() ) {
$this->AddSubscriberGroup($object);
}
elseif ( !$object->GetDBField('SubscribeToMailing') && $object->isSubscribed() ) {
$this->RemoveSubscriberGroup( $object->GetID() );
}
}
}
/**
* Stores user's original Status before overwriting with data from temp table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeDeleteFromLive(kEvent $event)
{
parent::OnBeforeDeleteFromLive($event);
$user_id = $event->getEventParam('id');
$user_status = $this->Application->GetVar('user_status', Array ());
if ( $user_id > 0 ) {
$user_status[$user_id] = $this->getUserStatus($user_id);
$this->Application->SetVar('user_status', $user_status);
}
}
/**
* Sends approved/declined email event on user status change (in temp tables during editing)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterCopyToLive(kEvent $event)
{
parent::OnAfterCopyToLive($event);
$temp_id = $event->getEventParam('temp_id');
$email_passwords = $this->Application->RecallVar('email_passwords');
if ( $email_passwords ) {
$email_passwords = unserialize($email_passwords);
if ( isset($email_passwords[$temp_id]) ) {
/** @var kDBItem $object */
$object = $event->getObject();
$object->SwitchToLive();
$object->Load( $event->getEventParam('id') );
$object->SetField('Password', $email_passwords[$temp_id]);
$object->SetField('VerifyPassword', $email_passwords[$temp_id]);
$this->Application->emailUser($temp_id > 0 ? 'USER.NEW.PASSWORD': 'USER.ADD.BYADMIN', $object->GetID());
unset($email_passwords[$temp_id]);
$this->Application->StoreVar('email_passwords', serialize($email_passwords));
}
}
if ( $temp_id > 0 ) {
// only send status change e-mail on user update
$new_status = $this->getUserStatus($temp_id);
$user_status = $this->Application->GetVar('user_status');
$this->sendStatusChangeEvent($temp_id, $user_status[$temp_id], $new_status);
}
}
/**
* Returns user status (active, pending, disabled) based on ID and temp mode setting
*
* @param int $user_id
* @return int
*/
function getUserStatus($user_id)
{
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
$sql = 'SELECT Status
FROM '.$table_name.'
WHERE '.$id_field.' = '.$user_id;
return $this->Conn->GetOne($sql);
}
/**
* Sends approved/declined email event on user status change
*
* @param int $user_id
* @param int $prev_status
* @param int $new_status
*/
function sendStatusChangeEvent($user_id, $prev_status, $new_status)
{
$status_events = Array (
STATUS_ACTIVE => 'USER.APPROVE',
STATUS_DISABLED => 'USER.DENY',
);
$email_event = isset($status_events[$new_status]) ? $status_events[$new_status] : false;
if (($prev_status != $new_status) && $email_event) {
$this->Application->emailUser($email_event, $user_id);
$this->Application->emailAdmin($email_event);
}
// deletes sessions from users, that are no longer active
if (($prev_status != $new_status) && ($new_status != STATUS_ACTIVE)) {
$sql = 'SELECT SessionId
FROM ' . TABLE_PREFIX . 'UserSessions
WHERE PortalUserId = ' . $user_id;
$session_ids = $this->Conn->GetCol($sql);
$this->Application->Session->DeleteSessions($session_ids);
}
}
/**
* Sends restore/validation email event on user email change
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function sendEmailChangeEvent(kEvent $event)
{
/** @var UsersItem $object */
$object = $event->getObject();
$new_email = $object->GetDBField('Email');
$prev_email = $object->GetOriginalField('Email');
if ( !$new_email || ($prev_email == $new_email) ) {
return;
}
$prev_emails = $object->GetDBField('PrevEmails');
$prev_emails = $prev_emails ? unserialize($prev_emails) : Array ();
$fields_hash = Array (
'PrevEmails' => serialize($prev_emails),
'EmailVerified' => 0,
);
$user_id = $object->GetID();
if ( $prev_email ) {
$hash = md5(TIMENOW + $user_id);
$prev_emails[$hash] = $prev_email;
$fields_hash['PrevEmails'] = serialize($prev_emails);
$send_params = Array (
'hash' => $hash,
'to_email' => $prev_email,
'to_name' => trim($object->GetDBField('FirstName') . ' ' . $object->GetDBField('LastName')),
);
$this->Application->emailUser('USER.EMAIL.CHANGE.UNDO', null, $send_params);
}
if ( $new_email ) {
$this->Application->emailUser('USER.EMAIL.CHANGE.VERIFY', $user_id);
}
// direct DB update, since USER.EMAIL.CHANGE.VERIFY puts verification code in user record, that we don't want to loose
$this->Conn->doUpdate($fields_hash, $object->TableName, 'PortalUserId = ' . $user_id);
}
/**
* OnAfterConfigRead for users
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$forms = $this->Application->getUnitOption($event->Prefix, 'Forms');
$form_fields =& $forms['default']['Fields'];
// 1. arrange user registration countries
/** @var SiteHelper $site_helper */
$site_helper = $this->Application->recallObject('SiteHelper');
$first_country = $site_helper->getDefaultCountry('', false);
if ($first_country === false) {
$first_country = $this->Application->ConfigValue('User_Default_Registration_Country');
}
if ($first_country) {
// update user country dropdown sql
$form_fields['Country']['options_sql'] = preg_replace('/ORDER BY (.*)/', 'ORDER BY IF (CountryStateId = '.$first_country.', 1, 0) DESC, \\1', $form_fields['Country']['options_sql']);
}
// 2. set default user registration group
$form_fields['PrimaryGroupId']['default'] = $this->Application->ConfigValue('User_NewGroup');
// 3. allow avatar upload on Front-End
/** @var FileHelper $file_helper */
$file_helper = $this->Application->recallObject('FileHelper');
$file_helper->createItemFiles($event->Prefix, true); // create image fields
if ($this->Application->isAdminUser) {
// 4. when in administrative console, then create all users with Active status
$form_fields['Status']['default'] = STATUS_ACTIVE;
// 5. remove groups tab on editing forms when AdvancedUserManagement config variable not set
if (!$this->Application->ConfigValue('AdvancedUserManagement')) {
$edit_tab_presets = $this->Application->getUnitOption($event->Prefix, 'EditTabPresets');
foreach ($edit_tab_presets as $preset_name => $preset_tabs) {
if (array_key_exists('groups', $preset_tabs)) {
unset($edit_tab_presets[$preset_name]['groups']);
if (count($edit_tab_presets[$preset_name]) == 1) {
// only 1 tab left -> remove it too
$edit_tab_presets[$preset_name] = Array ();
}
}
}
$this->Application->setUnitOption($event->Prefix, 'EditTabPresets', $edit_tab_presets);
}
}
if ( $this->Application->ConfigValue('RegistrationUsernameRequired') ) {
// Username becomes required only, when it's used in registration process
$max_username = $this->Application->ConfigValue('MaxUserName');
$form_fields['Username']['required'] = 1;
$form_fields['Username']['min_len'] = $this->Application->ConfigValue('Min_UserName');
$form_fields['Username']['max_len'] = $max_username ? $max_username : 255;
}
$this->Application->setUnitOption($event->Prefix, 'Forms', $forms);
}
/**
* OnMassCloneUsers
*
* @param kEvent $event
*/
function OnMassCloneUsers($event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$ids = $this->StoreSelectedIDs($event);
$temp_handler->CloneItems($event->Prefix, '', $ids);
$this->clearSelectedIDs($event);
}
/**
* When cloning users, reset password (set random)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeClone(kEvent $event)
{
parent::OnBeforeClone($event);
/** @var UsersItem $object */
$object = $event->getObject();
$object->generatePassword();
$object->SetDBField('ResourceId', 0); // this will reset it
// change email because it should be unique
$object->NameCopy(Array (), $object->GetID(), 'Email', 'copy%1$s.%2$s');
}
/**
* Saves selected ids to session
*
* @param kEvent $event
*/
function OnSaveSelected($event)
{
$this->StoreSelectedIDs($event);
// remove current ID, otherwise group selector will use it in filters
$this->Application->DeleteVar($event->getPrefixSpecial(true) . '_id');
}
/**
* Sets primary group of selected users
*
* @param kEvent $event
*/
function OnProcessSelected($event)
{
$event->SetRedirectParam('opener', 'u');
$user_ids = $this->getSelectedIDs($event, true);
$this->clearSelectedIDs($event);
$dst_field = $this->Application->RecallVar('dst_field');
if ( $dst_field != 'PrimaryGroupId' ) {
return;
}
$group_ids = array_keys($this->Application->GetVar('g'));
$primary_group_id = $group_ids ? array_shift($group_ids) : false;
if ( !$user_ids || !$primary_group_id ) {
return;
}
$table_name = $this->Application->getUnitOption('ug', 'TableName');
// 1. mark group as primary
$sql = 'UPDATE ' . TABLE_PREFIX . 'Users
SET PrimaryGroupId = ' . $primary_group_id . '
WHERE PortalUserId IN (' . implode(',', $user_ids) . ')';
$this->Conn->Query($sql);
foreach ( $user_ids as $user_id ) {
$this->Application->incrementCacheSerial('u', $user_id);
}
$this->Application->incrementCacheSerial('u');
$sql = 'SELECT PortalUserId
FROM ' . $table_name . '
WHERE (GroupId = ' . $primary_group_id . ') AND (PortalUserId IN (' . implode(',', $user_ids) . '))';
$existing_members = $this->Conn->GetCol($sql);
// 2. add new members to a group
$new_members = array_diff($user_ids, $existing_members);
foreach ($new_members as $user_id) {
$fields_hash = Array (
'GroupId' => $primary_group_id,
'PortalUserId' => $user_id,
);
$this->Conn->doInsert($fields_hash, $table_name);
}
}
/**
* Loads user images
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
// linking existing images for item with virtual fields
/** @var ImageHelper $image_helper */
$image_helper = $this->Application->recallObject('ImageHelper');
/** @var UsersItem $object */
$object = $event->getObject();
$image_helper->LoadItemImages($object);
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
$cs_helper->PopulateStates($event, 'State', 'Country');
// get user subscription status
$object->SetDBField('SubscribeToMailing', $object->isSubscribed() ? 1 : 0);
if ( !$this->Application->isAdmin ) {
$object->SetFieldOption('FrontLanguage', 'options', $this->getEnabledLanguages());
}
}
/**
* Returns list of enabled languages with their names
*
* @return Array
* @access protected
*/
protected function getEnabledLanguages()
{
$cache_key = 'user_languages[%LangSerial%]';
$ret = $this->Application->getCache($cache_key);
if ( $ret === false ) {
/** @var kDBList $languages */
$languages = $this->Application->recallObject('lang.enabled', 'lang_List');
$ret = Array ();
foreach ($languages as $language_info) {
$ret[$languages->GetID()] = $language_info['LocalName'];
}
$this->Application->setCache($cache_key, $ret);
}
return $ret;
}
/**
* Save user images
*
* @param kEvent $event
*/
function saveUserImages($event)
{
if (!$this->Application->isAdmin) {
/** @var ImageHelper $image_helper */
$image_helper = $this->Application->recallObject('ImageHelper');
/** @var kDBItem $object */
$object = $event->getObject();
// process image upload in virtual fields
$image_helper->SaveItemImages($object);
}
}
/**
* Makes password required for new users
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreCreate(kEvent $event)
{
parent::OnPreCreate($event);
if ( $event->status != kEvent::erSUCCESS ) {
return;
}
/** @var kDBItem $object */
$object = $event->getObject();
$user_type = $this->Application->GetVar('user_type');
if ( $user_type ) {
$object->SetDBField('UserType', $user_type);
if ( $user_type == UserType::ADMIN ) {
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_AdminGroup'));
}
}
if ( $this->Application->ConfigValue('User_Password_Auto') ) {
$object->SetDBField('EmailPassword', 1);
}
$this->_makePasswordRequired($event);
}
/**
* Makes password required for new users
*
* @param kEvent $event
*/
function _makePasswordRequired($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$required_fields = Array ('Password', 'Password_plain', 'VerifyPassword', 'VerifyPassword_plain');
$object->setRequired($required_fields);
}
/**
* Load item if id is available
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function LoadItem(kEvent $event)
{
$id = $this->getPassedID($event);
if ( $id < 0 ) {
// when root, guest and so on
/** @var kDBItem $object */
$object = $event->getObject();
$object->Clear($id);
return;
}
parent::LoadItem($event);
}
/**
* Occurs just after login (for hooking)
*
* @param kEvent $event
*/
function OnAfterLogin($event)
{
if ( is_object($event->MasterEvent) && !$this->Application->isAdmin ) {
$event->MasterEvent->SetRedirectParam('login', 1);
}
}
/**
* Occurs just before logout (for hooking)
*
* @param kEvent $event
*/
function OnBeforeLogout($event)
{
if ( is_object($event->MasterEvent) && !$this->Application->isAdmin ) {
$event->MasterEvent->SetRedirectParam('logout', 1);
}
}
/**
* Generates password
*
* @param kEvent $event
*/
function OnGeneratePassword($event)
{
$event->status = kEvent::erSTOP;
if ( $this->Application->isAdminUser ) {
echo kUtil::generatePassword();
}
}
/**
* Changes user's password and logges him in
*
* @param kEvent $event
*/
function OnResetLostPassword($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$event->CallSubEvent('OnUpdate');
if ( $event->status == kEvent::erSUCCESS ) {
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user =& $user_helper->getUserObject();
$user->Load( $object->GetID() );
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
/**
* Generates new Root password and email it
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetRootPassword($event)
{
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
$new_root_password = kUtil::generatePassword();
$this->Application->SetConfigValue('RootPass', $password_formatter->hashPassword($new_root_password));
$this->Application->emailAdmin('ROOT.RESET.PASSWORD', null, Array ('password' => $new_root_password));
$event->SetRedirectParam('reset', 1);
$event->SetRedirectParam('pass', 'm');
}
/**
* Perform login of user, selected in Admin Console, on Front-End in a separate window
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLoginAs(kEvent $event)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user =& $user_helper->getUserObject();
$user->Load( $this->Application->GetVar('user_id') );
if ( !$user->isLoaded() ) {
return ;
}
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
Index: branches/5.2.x/core/units/users/users_tag_processor.php
===================================================================
--- branches/5.2.x/core/units/users/users_tag_processor.php (revision 16803)
+++ branches/5.2.x/core/units/users/users_tag_processor.php (revision 16804)
@@ -1,378 +1,378 @@
<?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)
{
/** @var UsersItem $user */
$user = $this->Application->recallObject($this->Prefix . '.email-to');
$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(kUtil::generateId());
}
return $code;
}
function TestCodeIsValid($params)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('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 UsersItem $object */
$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)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('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 UsersItem $object */
$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)
{
/** @var UsersItem $object */
$object = $this->getObject($params);
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
+ $username = $this->Application->GetVarDirect('save_username', '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)
{
/** @var kPermissionsHelper $perm_helper */
$perm_helper = $this->Application->recallObject('PermissionsHelper');
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 ();
/** @var kDBList $object */
$object = $this->getObject($params);
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)
{
/** @var kDBItem $object */
$object = $this->getObject($params);
$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)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
/** @var UsersItem $user */
$user = $this->Application->recallObject($this->Prefix . '.activate', null, Array ('skip_autoload' => true));
$user->Load(trim($this->Application->GetVar('user_key')), 'PwResetConfirm');
if ( !$user->isLoaded() ) {
return ;
}
$user->SetDBFieldsFromHash($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() );
}
}
/**
* Returns user title
*
* @param array $params Parameters.
* @return string
* @access protected
*/
protected function UserTitle(array $params)
{
/** @var kDBItem $object */
$object = $this->getObject($params);
return $object->GetDBField('Email') ? $object->GetDBField('Email') : $object->GetDBField('Username');
}
}

Event Timeline