コード例 #1
0
 function handleFileDownload($contentObject, $contentObjectAttribute, $type, $fileInfo)
 {
     $fileName = $fileInfo['filepath'];
     $file = eZClusterFileHandler::instance($fileName);
     if ($fileName != "" and $file->exists()) {
         $fileSize = $file->size();
         if (isset($_SERVER['HTTP_RANGE']) && preg_match("/^bytes=(\\d+)-(\\d+)?\$/", trim($_SERVER['HTTP_RANGE']), $matches)) {
             $fileOffset = $matches[1];
             $contentLength = isset($matches[2]) ? $matches[2] - $matches[1] + 1 : $fileSize - $matches[1];
         } else {
             $fileOffset = 0;
             $contentLength = $fileSize;
         }
         // Figure out the time of last modification of the file right way to get the file mtime ... the
         $fileModificationTime = $file->mtime();
         // stop output buffering, and stop the session so that browsing can be continued while downloading
         eZSession::stop();
         ob_end_clean();
         eZFile::downloadHeaders($fileName, self::dispositionType($fileInfo['mime_type']) === 'attachment', false, $fileOffset, $contentLength, $fileSize);
         try {
             $file->passthrough($fileOffset, $contentLength);
         } catch (eZClusterFileHandlerNotFoundException $e) {
             eZDebug::writeError($e->getMessage, __METHOD__);
             header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error');
         } catch (eZClusterFileHandlerGeneralException $e) {
             eZDebug::writeError($e->getMessage, __METHOD__);
             header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
         }
         eZExecution::cleanExit();
     }
     return eZBinaryFileHandler::RESULT_UNAVAILABLE;
 }
 /**
  * Rate content object attribute id
  *
  * @param array $args ( 0 => contentobjectattribute_id,  1 => contentobject_version, 2 => rating )
  * @return array
  */
 public static function rate($args)
 {
     $ret = array('id' => 0, 'rated' => false, 'already_rated' => false, 'stats' => false);
     if (isset($args[0])) {
         $ret['id'] = $args[0];
     }
     if (!isset($args[2]) || !is_numeric($args[0]) || !is_numeric($args[1]) || !is_numeric($args[2]) || $args[2] > 5 || $args[2] < 1) {
         return $ret;
     }
     // Provide extra session protection on 4.1 (not possible on 4.0) by expecting user
     // to have an existing session (new session = mostlikely a spammer / hacker trying to manipulate rating)
     if (class_exists('eZSession') && eZSession::userHasSessionCookie() !== true) {
         return $ret;
     }
     // Return if parameters are not valid attribute id + version numbers
     $contentobjectAttribute = eZContentObjectAttribute::fetch($ret['id'], $args[1]);
     if (!$contentobjectAttribute instanceof eZContentObjectAttribute) {
         return $ret;
     }
     // Return if attribute is not a rating attribute
     if ($contentobjectAttribute->attribute('data_type_string') !== ezsrRatingType::DATA_TYPE_STRING) {
         return $ret;
     }
     // Return if rating has been disabled on current attribute
     if ($contentobjectAttribute->attribute('data_int')) {
         return $ret;
     }
     // Return if user does not have access to object
     $contentobject = $contentobjectAttribute->attribute('object');
     if (!$contentobject instanceof eZContentObject || !$contentobject->attribute('can_read')) {
         return $ret;
     }
     $rateDataObj = ezsrRatingDataObject::create(array('contentobject_id' => $contentobjectAttribute->attribute('contentobject_id'), 'contentobject_attribute_id' => $ret['id'], 'rating' => $args[2]));
     $proiorRating = $rateDataObj->userHasRated(true);
     if ($proiorRating === true) {
         $ret['already_rated'] = true;
     } else {
         if ($proiorRating instanceof ezsrRatingDataObject) {
             $rateDataObj = $proiorRating;
             $rateDataObj->setAttribute('rating', $args[2]);
             $ret['already_rated'] = true;
             $proiorRating = false;
             // just to reuse code bellow
         }
     }
     if (!$proiorRating) {
         $rateDataObj->store();
         $avgRateObj = $rateDataObj->getAverageRating();
         $avgRateObj->updateFromRatingData();
         $avgRateObj->store();
         eZContentCacheManager::clearContentCacheIfNeeded($rateDataObj->attribute('contentobject_id'));
         $ret['rated'] = true;
         $ret['stats'] = array('rating_count' => $avgRateObj->attribute('rating_count'), 'rating_average' => $avgRateObj->attribute('rating_average'), 'rounded_average' => $avgRateObj->attribute('rounded_average'));
     }
     return $ret;
 }
コード例 #3
0
 public function gc($maxLifeTime)
 {
     ezpEvent::getInstance()->notify('session/gc', array($maxLifeTime));
     $db = eZDB::instance();
     eZSession::triggerCallback('gc_pre', array($db, $maxLifeTime));
     $sfHandler = $this->storage->getSaveHandler();
     if (method_exists($sfHandler, 'gc')) {
         $sfHandler->gc($maxLifeTime);
     }
     eZSession::triggerCallback('gc_post', array($db, $maxLifeTime));
     return false;
 }
コード例 #4
0
ファイル: pre_check.php プロジェクト: rmiguel/ezpublish
/**
 * Check if user login is required. If so, use login handler to redirect user.
 *
 * @deprecated As of 4.4, moved to {@link eZUserLoginHandler::preCheck()}
 * @param array $siteBasics
 * @param eZURI $uri
 * @return array|true|false|null An associative array on redirect with 'module' and 'function' keys, true on successful
 *                               and false/null on #fail.
 */
function eZCheckUser(array &$siteBasics, eZURI $uri)
{
    if (!$siteBasics['user-object-required']) {
        return null;
    }
    $ini = eZINI::instance();
    $requireUserLogin = $ini->variable('SiteAccessSettings', 'RequireUserLogin') == 'true';
    $forceLogin = false;
    if (eZSession::hasStarted()) {
        $http = eZHTTPTool::instance();
        $forceLogin = $http->hasSessionVariable(eZUserLoginHandler::FORCE_LOGIN);
    }
    if (!$requireUserLogin && !$forceLogin) {
        return null;
    }
    return eZUserLoginHandler::checkUser($siteBasics, $uri);
}
コード例 #5
0
/**
 * Check if user login is required. If so, use login handler to redirect user.
 *
 * @deprecated As of 4.4, moved to {@link eZUserLoginHandler::preCheck()}
 * @param array $siteBasics
 * @param eZURI $uri
 * @return array|true|false|null An associative array on redirect with 'module' and 'function' keys, true on successful
 *                               and false/null on #fail.
 */
function eZCheckUser(array &$siteBasics, eZURI $uri)
{
    eZDebug::writeStrict('Function eZCheckUser() has been deprecated in 4.4 in favor of eZUserLoginHandler::preCheck()', 'Deprecation');
    if (!$siteBasics['user-object-required']) {
        return null;
    }
    $ini = eZINI::instance();
    $requireUserLogin = $ini->variable('SiteAccessSettings', 'RequireUserLogin') == 'true';
    $forceLogin = false;
    if (eZSession::hasStarted()) {
        $http = eZHTTPTool::instance();
        $forceLogin = $http->hasSessionVariable(eZUserLoginHandler::FORCE_LOGIN);
    }
    if (!$requireUserLogin && !$forceLogin) {
        return null;
    }
    return eZUserLoginHandler::checkUser($siteBasics, $uri);
}
コード例 #6
0
    /**
     * Rate content object attribute id
     *
     * @param array $args ( 0 => contentobjectattribute_id,  1 => contentobject_version, 2 => rating )
     * @return array
     */
    public static function rate( $args )
    {
        $ret = array( 'id' => 0, 'rated' => false, 'already_rated' => false, 'stats' => false );
        if ( !isset( $args[2] ) )
            throw new LengthException( 'Rating expects 3 arguments: attr_id, version, rating' );
        else if ( !is_numeric( $args[0] ) )
            throw new InvalidArgumentException( 'Rating argument[0] attr_id must be a number' );
        else if ( !is_numeric( $args[1] ) )
            throw new InvalidArgumentException( 'Rating argument[1] version must be a number' );
        else if ( !is_numeric( $args[2] ) )
            throw new InvalidArgumentException( 'Rating argument[2] rating must be a number' );
        else if ( $args[2] > 5 || $args[2] < 1 )
            throw new UnexpectedValueException( 'Rating argument[2] rating must be between 1 and 5' );

        $ret['id'] = (int) $args[0];

        // Provide extra session protection on 4.1 (not possible on 4.0) by expecting user
        // to have an existing session (new session = mostlikely a spammer / hacker trying to manipulate rating)
        if (
            eZSession::userHasSessionCookie() !== true
            && eZINI::instance()->variable( 'eZStarRating', 'AllowAnonymousRating' ) === 'disabled'
        )
            return $ret;

        // Return if parameters are not valid attribute id + version numbers
        $contentobjectAttribute = eZContentObjectAttribute::fetch( $ret['id'], $args[1] );
        if ( !$contentobjectAttribute instanceof eZContentObjectAttribute )
            return $ret;

        // Return if attribute is not a rating attribute
        if ( $contentobjectAttribute->attribute('data_type_string') !== ezsrRatingType::DATA_TYPE_STRING )
            return $ret;

        // Return if rating has been disabled on current attribute
        if ( $contentobjectAttribute->attribute('data_int') )
            return $ret;

        // Return if user does not have access to object
        $contentobject = $contentobjectAttribute->attribute('object');
        if ( !$contentobject instanceof eZContentObject || !$contentobject->attribute('can_read') )
            return $ret;

        $rateDataObj = ezsrRatingDataObject::create( array( 'contentobject_id' => $contentobjectAttribute->attribute('contentobject_id'),
                                                    'contentobject_attribute_id' =>  $ret['id'],
                                                    'rating' => $args[2]
        ));

        $proiorRating = $rateDataObj->userHasRated( true );

        if ( $proiorRating === true )
        {
            $ret['already_rated'] = true;
        }
        else if ( $proiorRating instanceof ezsrRatingDataObject )
        {
            $rateDataObj = $proiorRating;
            $rateDataObj->setAttribute( 'rating', $args[2] );
            $ret['already_rated'] = true;
            $proiorRating = false;// just to reuse code bellow
        }

        if ( !$proiorRating )
        {
            $rateDataObj->store();
            $avgRateObj = $rateDataObj->getAverageRating();
            $avgRateObj->updateFromRatingData();
            $avgRateObj->store();
            eZContentCacheManager::clearContentCacheIfNeeded( $rateDataObj->attribute('contentobject_id') );
            $ret['rated'] = true;
            $ret['stats'] = array(
               'rating_count' => $avgRateObj->attribute('rating_count'),
               'rating_average' => $avgRateObj->attribute('rating_average'),
               'rounded_average' => $avgRateObj->attribute('rounded_average'),
            );
        }
        return $ret;
    }
コード例 #7
0
ファイル: action.php プロジェクト: gggeek/ggwebservices
         }
         break;
     default:
         // give a warning
         $actionname = '[ERROR: unknown action] "' . $action . '"';
 }
 // Before calling execute, echo out brief description of action taken + date and time ???
 // this gives good user feedback for long-running methods...
 /// @todo use a template for html layout
 if ($action != 'inspect' || $debug) {
     echo '<h2>' . htmlspecialchars($actionname) . ' on server ' . htmlspecialchars($server) . " ...</h2>\n";
     flush();
 }
 // avoid locking in case we are using a session for executing the action which
 // is the sane session as used by the debugger and plain php session storage
 eZSession::stop();
 // execute method(s)
 $response = null;
 $responses = array();
 $time = microtime(true);
 foreach ($msg as $message) {
     $response = $client->send($message);
     $responses[] = $response;
     if (!is_object($response) || $response->isFault()) {
         break;
     }
 }
 $time = microtime(true) - $time;
 if ($debug) {
     /// @todo should echo the request+response of all requests, when sending more than 1
     echo '<div class="dbginfo"><h2>Debug info:</h2>';
コード例 #8
0
 /**
  * Remove all session data (Truncate table)
  *
  * @return bool
  */
 public function cleanup()
 {
     $db = eZDB::instance();
     eZSession::triggerCallback('cleanup_pre', array($db));
     $db->query('TRUNCATE TABLE ezsession');
     eZSession::triggerCallback('cleanup_post', array($db));
     return true;
 }
コード例 #9
0
ファイル: ezxformtoken.php プロジェクト: nlescure/ezpublish
 /**
  * Figures out if current user should be protected or not
  * based on if (s)he has a session and is logged in.
  *
  * @return bool
  */
 protected static function shouldProtectUser()
 {
     if (!eZSession::hasStarted()) {
         return false;
     }
     if (!eZUser::currentUser()->isLoggedIn()) {
         return false;
     }
     return true;
 }
コード例 #10
0
ファイル: login.php プロジェクト: robinmuilwijk/ezpublish
    $userID = 0;
    if ( $user instanceof eZUser )
        $userID = $user->id();
    if ( $userID > 0 )
    {
        if ( $http->hasPostVariable( 'Cookie' ) )
        {
            $ini = eZINI::instance();
            $rememberMeTimeout = $ini->hasVariable( 'Session', 'RememberMeTimeout' )
                                 ? $ini->variable( 'Session', 'RememberMeTimeout' )
                                 : false;
            if ( $rememberMeTimeout )
            {
                eZSession::stop();
                eZSession::start( $rememberMeTimeout );
            }

        }
        $http->removeSessionVariable( 'eZUserLoggedInID' );
        $http->setSessionVariable( 'eZUserLoggedInID', $userID );

        // Remove all temporary drafts
        eZContentObject::cleanupAllInternalDrafts( $userID );
        return $Module->redirectTo( $redirectionURI );
    }
}
else
{
    // called from outside of a template (?)
    $requestedURI = $GLOBALS['eZRequestedURI'];
コード例 #11
0
 function checkUser(&$siteBasics, $uri)
 {
     $http = eZHTTPTool::instance();
     $check = array("module" => "user", "function" => "login");
     if (eZSession::issetkey('eZUserLoggedInID', false) && $http->sessionVariable("eZUserLoggedInID") != '' && $http->sessionVariable("eZUserLoggedInID") != self::anonymousId()) {
         $currentUser = eZUser::currentUser();
         if (!$currentUser->isEnabled()) {
             eZUser::logoutCurrent();
             $currentUser = eZUser::currentUser();
         } else {
             return null;
         }
     }
     $ini = eZINI::instance();
     $moduleName = $uri->element();
     $viewName = $uri->element(1);
     $anonymousAccessList = $ini->variable("SiteAccessSettings", "AnonymousAccessList");
     foreach ($anonymousAccessList as $anonymousAccess) {
         $elements = explode('/', $anonymousAccess);
         if (!isset($elements[1])) {
             if ($moduleName == $elements[0]) {
                 return null;
             }
         } else {
             if ($moduleName == $elements[0] and $viewName == $elements[1]) {
                 return null;
             }
         }
     }
     return $check;
 }
コード例 #12
0
ファイル: ezsession.php プロジェクト: legende91/ez
 /**
  * Get curren session handler
  *
  * @since 4.4
  * @return ezpSessionHandler
  */
 public static function getHandlerInstance()
 {
     if (self::$handlerInstance === null) {
         $ini = eZINI::instance();
         if ($ini->variable('Session', 'Handler') !== '') {
             $optionArray = array('iniFile' => 'site.ini', 'iniSection' => 'Session', 'iniVariable' => 'Handler', 'handlerParams' => array(self::$hasSessionCookie));
             $options = new ezpExtensionOptions($optionArray);
             self::$handlerInstance = eZExtension::getHandlerClass($options);
         }
         if (!self::$handlerInstance instanceof ezpSessionHandler) {
             self::$handlerInstance = new ezpSessionHandlerPHP(self::$hasSessionCookie);
         }
     }
     return self::$handlerInstance;
 }
コード例 #13
0
 /**
  * Figures out if current user should be protected or not
  * based on if (s)he has a session and is logged in.
  *
  * @return bool
  */
 protected static function shouldProtectUser()
 {
     if (!self::$isEnabled) {
         return false;
     }
     if (!eZSession::hasStarted()) {
         return false;
     }
     if (!eZUser::isCurrentUserRegistered()) {
         return false;
     }
     return true;
 }
コード例 #14
0
/**
 * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
 * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
 * @version //autogentag//
 * @package kernel
 */
$tpl = eZTemplate::factory();
$http = eZHTTPTool::instance();
$Offset = $Params['Offset'];
if (!is_numeric($Offset)) {
    $Offset = 0;
}
$parents = array();
// Make sure user has session (if not, then this can't possible be a valid browse request)
if (!eZSession::userHasSessionCookie()) {
    return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
}
// Check that Browse parameters exists
if (!$http->hasSessionVariable('BrowseParameters')) {
    return $Module->handleError(eZError::KERNEL_NOT_FOUND, 'kernel');
}
// Check if node parameters exist
$browse = new eZContentBrowse();
if (!isset($Params['NodeID']) && !isset($Params['NodeList']) && !$browse->hasAttribute('start_node')) {
    return $Module->handleError(eZError::KERNEL_NOT_FOUND, 'kernel');
}
// We get node list when browse is execiuted from search engine ( "search in browse" functionality )
if (isset($Params['NodeList'])) {
    $nodeList = $Params['NodeList']['SearchResult'];
    $nodeListCount = $Params['NodeList']['SearchCount'];
コード例 #15
0
//
// Definition of Session_GC Cronjob
/**
 * File containing the session_gc.php cronjob
 *
 * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
 * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
 * @version //autogentag//
 * @package kernel
 */
/**
 * Cronjob to garbage collect expired sessions as defined by site.ini[Session]SessionTimeout
 * (the expiry time is calculated when session is created / updated)
 * These are normally automatically removed by the session gc in php, but on some linux distroes
 * based on debian this does not work because the custom way session gc is handled.
 *
 * Also make sure you run basket_cleanup if you use the shop!
 *
 * @package eZCronjob
 * @see eZsession
 */
// Functions for session to make sure baskets are cleaned up
function eZSessionBasketGarbageCollector($db, $time)
{
    eZBasket::cleanupExpired($time);
}
// Fill in hooks
eZSession::addCallback('gc_pre', 'eZSessionBasketGarbageCollector');
eZSession::garbageCollector();
コード例 #16
0
 /**
  * reimp (not used in this handler)
  */
 public function cleanup()
 {
     $db = eZDB::instance();
     eZSession::triggerCallback('cleanup_pre', array($db));
     eZSession::triggerCallback('cleanup_post', array($db));
     return true;
 }
コード例 #17
0
ファイル: index.php プロジェクト: legende91/ez
        $tpl = eZTemplate::factory();
        if (empty($warningList)) {
            $warningList = false;
        }
        $tpl->setVariable('site', $site);
        $tpl->setVariable('warning_list', $warningList);
        $tpl->setVariable('redirect_uri', eZURI::encodeURL($redirectURI));
        $templateResult = $tpl->fetch('design:redirect.tpl');
        eZDebug::addTimingPoint("Script end");
        eZDisplayResult($templateResult);
    }
    eZExecution::cleanExit();
}
// Store the last URI for access history for login redirection
// Only if user has session and only if there was no error or no redirects happen
if (eZSession::hasStarted() && $module->exitStatus() == eZModule::STATUS_OK) {
    $currentURI = $completeRequestedURI;
    if (strlen($currentURI) > 0 and $currentURI[0] != '/') {
        $currentURI = '/' . $currentURI;
    }
    $lastAccessedURI = "";
    $lastAccessedViewURI = "";
    $http = eZHTTPTool::instance();
    // Fetched stored session variables
    if ($http->hasSessionVariable("LastAccessesURI")) {
        $lastAccessedViewURI = $http->sessionVariable("LastAccessesURI");
    }
    if ($http->hasSessionVariable("LastAccessedModifyingURI")) {
        $lastAccessedURI = $http->sessionVariable("LastAccessedModifyingURI");
    }
    // Update last accessed view page
コード例 #18
0
ファイル: index.php プロジェクト: runelangseid/ezpublish
        $tpl = eZTemplate::factory();
        if (count($warningList) == 0) {
            $warningList = false;
        }
        $tpl->setVariable('site', $site);
        $tpl->setVariable('warning_list', $warningList);
        $tpl->setVariable('redirect_uri', eZURI::encodeURL($redirectURI));
        $templateResult = $tpl->fetch('design:redirect.tpl');
        eZDebug::addTimingPoint("End");
        eZDisplayResult($templateResult);
    }
    eZExecution::cleanExit();
}
// Store the last URI for access history for login redirection
// Only if database is connected, user has session and only if there was no error or no redirects happen
if (eZSession::hasStarted() && is_object($db) && $db->isConnected() && $module->exitStatus() == eZModule::STATUS_OK) {
    $currentURI = $completeRequestedURI;
    if (strlen($currentURI) > 0 and $currentURI[0] != '/') {
        $currentURI = '/' . $currentURI;
    }
    $lastAccessedURI = "";
    $lastAccessedViewURI = "";
    $http = eZHTTPTool::instance();
    // Fetched stored session variables
    if ($http->hasSessionVariable("LastAccessesURI")) {
        $lastAccessedViewURI = $http->sessionVariable("LastAccessesURI");
    }
    if ($http->hasSessionVariable("LastAccessedModifyingURI")) {
        $lastAccessedURI = $http->sessionVariable("LastAccessedModifyingURI");
    }
    // Update last accessed view page
コード例 #19
0
ファイル: index.php プロジェクト: robinmuilwijk/ezpublish
        $tpl->setVariable( 'site', $site );
        $tpl->setVariable( 'warning_list', $warningList );
        $tpl->setVariable( 'redirect_uri', eZURI::encodeURL( $redirectURI ) );
        $templateResult = $tpl->fetch( 'design:redirect.tpl' );

        eZDebug::addTimingPoint( "End" );

        eZDisplayResult( $templateResult );
    }

    eZExecution::cleanExit();
}

// Store the last URI for access history for login redirection
// Only if user has session and only if there was no error or no redirects happen
if ( eZSession::hasStarted() &&
    $module->exitStatus() == eZModule::STATUS_OK )
{
    $currentURI = $completeRequestedURI;
    if ( strlen( $currentURI ) > 0 and $currentURI[0] != '/' )
        $currentURI = '/' . $currentURI;

    $lastAccessedURI = "";
    $lastAccessedViewURI = "";

    $http = eZHTTPTool::instance();

    // Fetched stored session variables
    if ( $http->hasSessionVariable( "LastAccessesURI" ) )
    {
        $lastAccessedViewURI = $http->sessionVariable( "LastAccessesURI" );
コード例 #20
0
ファイル: session.php プロジェクト: CG77/ezpublish-legacy
    if (strlen($filterSQL) + strlen($expirationFilterSQL) > 0) {
        $whereSQL = 'WHERE';
    }
    $db = eZDB::instance();
    $query = "SELECT count( DISTINCT ezsession.user_id ) AS count\n              FROM ezsession\n              {$whereSQL}\n              {$filterSQL}\n              {$expirationFilterSQL}";
    $rows = $db->arrayQuery($query);
    return $rows[0]['count'];
}
$param['sortby'] = false;
$param['filter_type'] = $filterType;
$param['expiration_filter'] = $expirationFilterType;
$param['user_id'] = $userID;
if (isset($viewParameters['sortby'])) {
    $param['sortby'] = $viewParameters['sortby'];
}
$sessionsActive = eZSession::countActive();
$sessionsCount = eZFetchActiveSessionCount($param);
$sessionsList = eZFetchActiveSessions($param);
if ($param['offset'] >= $sessionsActive and $sessionsActive != 0) {
    $module->redirectTo('/setup/session');
}
$tpl->setVariable("gc_sessions_completed", $gcSessionsCompleted);
$tpl->setVariable("sessions_removed", $sessionsRemoved);
$tpl->setVariable("sessions_active", $sessionsActive);
$tpl->setVariable("sessions_count", $sessionsCount);
$tpl->setVariable("sessions_list", $sessionsList);
$tpl->setVariable("page_limit", $param['limit']);
$tpl->setVariable("view_parameters", $viewParameters);
$tpl->setVariable("form_parameter_string", $viewParameters);
$tpl->setVariable('filter_type', $filterType);
$tpl->setVariable('expiration_filter_type', $expirationFilterType);
コード例 #21
0
    /**
     * Remove all session data (Truncate table)
     *
     * @return bool
     */
    public function cleanup()
    {
        ezpEvent::getInstance()->notify( 'session/cleanup', array() );
        $db = eZDB::instance();

        eZSession::triggerCallback( 'cleanup_pre', array( $db ) );
        $db->query( 'TRUNCATE TABLE ezsession' );
        eZSession::triggerCallback( 'cleanup_post', array( $db ) );

        return true;
    }
コード例 #22
0
 protected function requestInit()
 {
     if ($this->isInitialized) {
         return;
     }
     eZExecution::setCleanExit(false);
     $scriptStartTime = microtime(true);
     $GLOBALS['eZRedirection'] = false;
     $this->access = eZSiteAccess::current();
     eZDebug::setScriptStart($scriptStartTime);
     eZDebug::addTimingPoint("Script start");
     $this->uri = eZURI::instance(eZSys::requestURI());
     $GLOBALS['eZRequestedURI'] = $this->uri;
     // Be able to do general events early in process
     ezpEvent::getInstance()->notify('request/preinput', array($this->uri));
     // Initialize module loading
     $this->siteBasics['module-repositories'] = eZModule::activeModuleRepositories();
     eZModule::setGlobalPathList($this->siteBasics['module-repositories']);
     // make sure we get a new $ini instance now that it has been reset
     $ini = eZINI::instance();
     // start: eZCheckValidity
     // pre check, setup wizard related so needs to be before session/db init
     // TODO: Move validity check in the constructor? Setup is not meant to be launched at each (sub)request is it?
     if ($ini->variable('SiteAccessSettings', 'CheckValidity') === 'true') {
         $this->check = array('module' => 'setup', 'function' => 'init');
         // Turn off some features that won't bee needed yet
         $this->siteBasics['policy-check-omit-list'][] = 'setup';
         $this->siteBasics['show-page-layout'] = $ini->variable('SetupSettings', 'PageLayout');
         $this->siteBasics['validity-check-required'] = true;
         $this->siteBasics['session-required'] = $this->siteBasics['user-object-required'] = false;
         $this->siteBasics['db-required'] = $this->siteBasics['no-cache-adviced'] = $this->siteBasics['url-translator-allowed'] = false;
         $this->siteBasics['site-design-override'] = $ini->variable('SetupSettings', 'OverrideSiteDesign');
         $this->access = eZSiteAccess::change(array('name' => 'setup', 'type' => eZSiteAccess::TYPE_URI));
         eZTranslatorManager::enableDynamicTranslations();
     }
     // stop: eZCheckValidity
     if ($this->siteBasics['session-required']) {
         // Check if this should be run in a cronjob
         if ($ini->variable('Session', 'BasketCleanup') !== 'cronjob') {
             eZSession::addCallback('destroy_pre', function (eZDBInterface $db, $key, $escapedKey) {
                 $basket = eZBasket::fetch($key);
                 if ($basket instanceof eZBasket) {
                     $basket->remove();
                 }
             });
             eZSession::addCallback('gc_pre', function (eZDBInterface $db, $time) {
                 eZBasket::cleanupExpired($time);
             });
             eZSession::addCallback('cleanup_pre', function (eZDBInterface $db) {
                 eZBasket::cleanup();
             });
         }
         // addCallBack to update session id for shop basket on session regenerate
         eZSession::addCallback('regenerate_post', function (eZDBInterface $db, $escNewKey, $escOldKey) {
             $db->query("UPDATE ezbasket SET session_id='{$escNewKey}' WHERE session_id='{$escOldKey}'");
         });
         // TODO: Session starting should be made only once in the constructor
         $this->sessionInit();
     }
     // if $this->siteBasics['db-required'], open a db connection and check that db is connected
     if ($this->siteBasics['db-required'] && !eZDB::instance()->isConnected()) {
         $this->warningList[] = array('error' => array('type' => 'kernel', 'number' => eZError::KERNEL_NO_DB_CONNECTION), 'text' => 'No database connection could be made, the system might not behave properly.');
     }
     // eZCheckUser: pre check, RequireUserLogin & FORCE_LOGIN related so needs to be after session init
     if (!isset($this->check)) {
         $this->check = eZUserLoginHandler::preCheck($this->siteBasics, $this->uri);
     }
     ezpEvent::getInstance()->notify('request/input', array($this->uri));
     // Initialize with locale settings
     // TODO: Move to constructor? Is it relevant to init the locale/charset for each (sub)requests?
     $this->languageCode = eZLocale::instance()->httpLocaleCode();
     $phpLocale = trim($ini->variable('RegionalSettings', 'SystemLocale'));
     if ($phpLocale != '') {
         setlocale(LC_ALL, explode(',', $phpLocale));
     }
     $this->httpCharset = eZTextCodec::httpCharset();
     // TODO: are these parameters supposed to vary across potential sub-requests?
     $this->site = array('title' => $ini->variable('SiteSettings', 'SiteName'), 'design' => $ini->variable('DesignSettings', 'SiteDesign'), 'http_equiv' => array('Content-Type' => 'text/html; charset=' . $this->httpCharset, 'Content-language' => $this->languageCode));
     // Read role settings
     $this->siteBasics['policy-check-omit-list'] = array_merge($this->siteBasics['policy-check-omit-list'], $ini->variable('RoleSettings', 'PolicyOmitList'));
     $this->isInitialized = true;
 }
コード例 #23
0
 /**
  * Prepares a file for Download and terminates the execution.
  * This method will:
  * - empty the output buffer
  * - stop buffering
  * - stop the active session (in order to allow concurrent browsing while downloading)
  *
  * @param string $file Path to the local file
  * @param bool $isAttachedDownload Determines weather to download the file as an attachment ( download popup box ) or not.
  * @param string $overrideFilename
  * @param int $startOffset Offset to start transfer from, in bytes
  * @param int $length Data size to transfer
  *
  * @return bool false if error
  */
 static function download($file, $isAttachedDownload = true, $overrideFilename = false, $startOffset = 0, $length = false)
 {
     if (!file_exists($file)) {
         return false;
     }
     ob_end_clean();
     eZSession::stop();
     self::downloadHeaders($file, $isAttachedDownload, $overrideFilename, $startOffset, $length);
     self::downloadContent($file, $startOffset, $length);
     eZExecution::cleanExit();
 }
コード例 #24
0
ファイル: ezscript.php プロジェクト: nlescure/ezpublish
 function shutdown($exitCode = false, $exitText = false)
 {
     $cli = eZCLI::instance();
     if (class_exists('eZDB') and eZDB::hasInstance()) {
         $db = eZDB::instance(false, array('show_errors' => false));
         // Perform transaction check
         $transactionCounterCheck = eZDB::checkTransactionCounter();
         if (isset($transactionCounterCheck['error'])) {
             $cli->error($transactionCounterCheck['error']);
         }
         if ($this->UseSession and $db->isConnected()) {
             eZUser::logoutCurrent();
             eZSession::remove();
         }
     }
     $webOutput = $cli->isWebOutput();
     if ($this->UseDebugOutput or eZDebug::isDebugEnabled()) {
         if ($this->DebugMessage) {
             fputs(STDERR, $this->DebugMessage);
         }
         fputs(STDERR, eZDebug::printReport(false, $webOutput, true, $this->AllowedDebugLevels, $this->UseDebugAccumulators, $this->UseDebugTimingPoints, $this->UseIncludeFiles));
     }
     eZExecution::cleanup();
     eZExecution::setCleanExit();
     $this->setIsInitialized(false);
     if ($exitCode !== false) {
         $this->ExitCode = $exitCode;
     }
     if ($this->ExitCode !== false) {
         if ($exitText !== false) {
             $cli->output($exitText);
         }
         exit($this->ExitCode);
     }
 }
コード例 #25
0
ファイル: register.php プロジェクト: jordanmanning/ezpublish
 $userClientValidates = true;
 $doValidationRedirect = false;
 if (!eZSession::userHasSessionCookie()) {
     if ($redirectNumber == '2') {
         $userClientValidates = false;
     } else {
         $doValidationRedirect = true;
     }
 }
 if ($doValidationRedirect) {
     $db->rollback();
     return $Module->redirectTo('/user/register/2');
 } else {
     if (!$userClientValidates) {
         $db->rollback();
         $tpl->setVariable('user_has_cookie', eZSession::userHasSessionCookie(), 'User');
         $tpl->setVariable('user_session_validates', true, 'User');
         $Result = array();
         $Result['content'] = $tpl->fetch('design:user/register_user_not_valid.tpl');
         $Result['path'] = array(array('url' => false, 'text' => ezpI18n::tr('kernel/user', 'User')), array('url' => false, 'text' => ezpI18n::tr('kernel/user', 'Register')));
         return $Result;
     }
 }
 // else create user object
 if ($http->hasSessionVariable('StartedRegistration')) {
     eZDebug::writeWarning('Cancel module run to protect against multiple form submits', 'user/register');
     $http->removeSessionVariable("RegisterUserID");
     $http->removeSessionVariable('StartedRegistration');
     $db->commit();
     return eZModule::HOOK_STATUS_CANCEL_RUN;
 } else {
コード例 #26
0
     $postData = $lastPostVars;
     $http->setSessionVariable('LastPostVars', $lastPostVars);
 }
 $user = false;
 if ($userLogin != '') {
     if ($http->hasSessionVariable("RedirectAfterLogin", false)) {
         $http->removeSessionVariable('RedirectAfterLogin');
     }
     if ($ini->hasVariable('UserSettings', 'LoginHandler')) {
         $loginHandlers = $ini->variable('UserSettings', 'LoginHandler');
     } else {
         $loginHandlers = array('standard');
     }
     $hasAccessToSite = true;
     if ($http->hasPostVariable('Cookie') && $ini->hasVariable('Session', 'RememberMeTimeout') && ($rememberMeTimeout = $ini->variable('Session', 'RememberMeTimeout'))) {
         eZSession::setCookieLifetime($rememberMeTimeout);
     }
     foreach (array_keys($loginHandlers) as $key) {
         $loginHandler = $loginHandlers[$key];
         $userClass = eZUserLoginHandler::instance($loginHandler);
         if (!is_object($userClass)) {
             continue;
         }
         $user = $userClass->loginUser($userLogin, $userPassword);
         if ($user instanceof eZUser) {
             $hasAccessToSite = $user->canLoginToSiteAccess($GLOBALS['eZCurrentAccess']);
             if (!$hasAccessToSite) {
                 $user->logoutCurrent();
                 $user = null;
                 $siteAccessName = $GLOBALS['eZCurrentAccess']['name'];
                 $siteAccessAllowed = false;
コード例 #27
0
        $cli->output( "Removing all sessions" );
        eZSession::cleanup();
    }
}

if ( $clean['expired_session'] )
{
    if ( !eZSession::getHandlerInstance()->hasBackendAccess() )
    {
        $cli->output( "Could not remove expired sessions, current session handler does not support session garbage collection (not backend based)." );
    }
    else
    {
        $cli->output( "Removing expired sessions,", false );
        eZSession::garbageCollector();
        $activeCount = eZSession::countActive();
        $cli->output( " " . $cli->stylize( 'emphasize', $activeCount ) . " left" );
    }
}

if ( $clean['preferences'] )
{
    $cli->output( "Removing all preferences" );
    eZPreferences::cleanup();
}

if ( $clean['browse'] )
{
    $cli->output( "Removing all recent items and bookmarks for browse page" );
    eZContentBrowseRecent::cleanup();
    eZContentBrowseBookmark::cleanup();
コード例 #28
0
 /**
  * Get session variable $name
  *
  * @param string $name
  * @param mixed $fallbackValue Return this if session has not started OR name is undefined
  *              if null(default), then force start session and return null if undefined.
  * @return mixed ByRef
  */
 function &sessionVariable($name, $fallbackValue = null)
 {
     return eZSession::get($name, $fallbackValue);
 }
コード例 #29
0
// load siteaccess
$access = eZSiteAccess::match( $uri,
                      eZSys::hostname(),
                      eZSys::serverPort(),
                      eZSys::indexFile() );
$access = eZSiteAccess::change( $access );
$GLOBALS['eZCurrentAccess'] = $access;

// Check for new extension loaded by siteaccess
eZExtension::activateExtensions( 'access' );

$db = eZDB::instance();
if ( $db->isConnected() )
{
    eZSession::start();
}
else
{
    exitWithInternalError();
    return;
}

$moduleINI = eZINI::instance( 'module.ini' );
$globalModuleRepositories = $moduleINI->variable( 'ModuleSettings', 'ModuleRepositories' );
eZModule::setGlobalPathList( $globalModuleRepositories );

$module = eZModule::exists( 'content' );
if ( !$module )
{
    exitWithInternalError();
コード例 #30
0
ファイル: login.php プロジェクト: legende91/ez
     $postData = $lastPostVars;
     $http->setSessionVariable('LastPostVars', $lastPostVars);
 }
 $user = false;
 if ($userLogin != '') {
     if ($http->hasSessionVariable("RedirectAfterLogin", false)) {
         $http->removeSessionVariable('RedirectAfterLogin');
     }
     if ($ini->hasVariable('UserSettings', 'LoginHandler')) {
         $loginHandlers = $ini->variable('UserSettings', 'LoginHandler');
     } else {
         $loginHandlers = array('standard');
     }
     $hasAccessToSite = true;
     if ($http->hasPostVariable('Cookie') && $ini->hasVariable('Session', 'RememberMeTimeout') && ($rememberMeTimeout = $ini->variable('Session', 'RememberMeTimeout'))) {
         eZSession::setCookieParams($rememberMeTimeout);
     }
     foreach (array_keys($loginHandlers) as $key) {
         $loginHandler = $loginHandlers[$key];
         $userClass = eZUserLoginHandler::instance($loginHandler);
         if (!is_object($userClass)) {
             continue;
         }
         $user = $userClass->loginUser($userLogin, $userPassword);
         if ($user instanceof eZUser) {
             $hasAccessToSite = $user->canLoginToSiteAccess($GLOBALS['eZCurrentAccess']);
             if (!$hasAccessToSite) {
                 $user->logoutCurrent();
                 $user = null;
                 $siteAccessName = $GLOBALS['eZCurrentAccess']['name'];
                 $siteAccessAllowed = false;