By registering a fatal error handler it's possible for the PHP script to catch fatal errors, such as "Call to a member function on a non-object". By registering a cleanup handler it's possible to make sure the script can end properly.
    public static function redirectToErrorPage()
    {
        $acessErrorPage = '/page/gift-law';

        header( 'Location: ' . $acessErrorPage );
        eZExecution::cleanExit();
    }
 /**
  * Creates a new test database
  *
  * @param ezpDsn $dsn
  * @param array $sqlFiles array( array( string => string ) )
  * @param bool $removeExisting
  * @return mixed
  */
 public static function create(ezpDsn $dsn)
 {
     //oracle unit test doesn't support creating database, just use database string
     if ($dsn->parts['phptype'] === 'oracle') {
         $db = ezpDatabaseHelper::useDatabase($dsn);
         eZDBTool::cleanup($db);
         return $db;
     }
     $dsnRoot = clone $dsn;
     $dsnRoot->parts['database'] = null;
     try {
         $dbRoot = ezpDatabaseHelper::dbAsRootInstance($dsnRoot);
         if (!$dbRoot->IsConnected) {
             throw new Exception($dbRoot->ErrorMessage);
         }
     } catch (Exception $e) {
         echo $e->getMessage() . PHP_EOL;
         eZExecution::cleanExit();
     }
     if (self::exists($dbRoot, $dsn->database)) {
         $db = ezpDatabaseHelper::useDatabase($dsn);
         self::clean($db);
     } else {
         $dbRoot->createDatabase($dsn->database);
         $db = ezpDatabaseHelper::useDatabase($dsn);
     }
     return $db;
 }
 public function __construct()
 {
     $ini = eZINI::instance('mugo_varnish.ini');
     if ($ini->hasVariable('PurgeUrlBuilder', 'PathPrefixModifier')) {
         $this->pathPrefixModifier = $ini->variable('PurgeUrlBuilder', 'PathPrefixModifier');
     }
     if ($ini->hasVariable('PurgeUrlBuilder', 'UriTransformation')) {
         $this->uriTransformation = $ini->variable('PurgeUrlBuilder', 'UriTransformation') == 'enabled' ? true : false;
     }
     if ($ini->hasVariable('PurgeUrlBuilder', 'ModifierMatch')) {
         $this->urlModifierMatch = $ini->variable('PurgeUrlBuilder', 'ModifierMatch');
         $this->urlModifierReplace = $ini->variable('PurgeUrlBuilder', 'ModifierReplace');
     }
     if ($ini->hasVariable('PurgeUrlBuilder', 'OmitUrlPatterns')) {
         $this->omitUrlPatterns = $ini->variable('PurgeUrlBuilder', 'OmitUrlPatterns');
     }
     if ($ini->hasVariable('PurgeUrlBuilder', 'PurgeSystemURL')) {
         $this->purgeSystemUrls = $ini->variable('PurgeUrlBuilder', 'PurgeSystemURL') == 'enabled' ? true : false;
     }
     // Register Cleanup Hanlder to purge urls at the end of the request
     if (!self::$cleanUpHandlerRegistered) {
         self::$cleanUpHandlerRegistered = true;
         eZExecution::addCleanupHandler(array('MugoVarnishCleanUpHandler', 'purgeList'));
     }
 }
 public static function trackTransaction()
 {
     eZExecution::addCleanupHandler(function () {
         $newrelic = new Newrelic(true);
         $newrelic->nameTransaction(self::buildCurrentTransactionName());
     });
 }
 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;
 }
예제 #6
0
 /**
  *
  * Builds the response-data.
  *
  * @return mixed|void
  *
  */
 public function run()
 {
     $content = $this->content;
     $status = $this->options['status'];
     $options = $this->options;
     // Give response header for status code
     header('HTTP/1.1 ' . $status . ' ' . $this->codes[$status]);
     switch ($options['type']) {
         case 'json':
             $options['headers'] += array('Content-type' => 'application/json');
             $this->headers($options['headers']);
             echo json_encode($content);
             break;
         case 'jsonEncoded':
             $options['headers'] += array('Content-type' => 'application/json');
             $this->headers($options['headers']);
             return compact('content');
         case 'tpl':
             /** Default pagelayout. */
             $options += array('pagelayout' => 'pagelayout.tpl');
             return $this->renderTpl($content, $options);
         case 'text':
             return array('pagelayout' => false, 'content' => $this->content);
         case 'xml':
             $options['headers'] += array('Content-type' => 'text/xml');
             $this->headers($options['headers']);
             echo $content;
             break;
     }
     Router::handleEZXFormToken(true);
     return \eZExecution::cleanExit();
 }
예제 #7
0
    /**
     * @param string $clusterIdentifier
     * @throws eZDBException
     */
    public static function fill($clusterIdentifier)
    {
        $configPath = "extension/ezoscar/bin/php/seo/config.json";
        $cli = eZCLI::instance();

        $config = file_get_contents($configPath);
        if(!$config)
        {
            $cli->output("Bad filepath for config file");
            eZExecution::cleanExit();
        }

        $config = json_decode($config, true);

        $db = MMDB::instance();

        $rows = $db->arrayQuery(sprintf("SELECT * FROM mm_seo WHERE cluster_identifier = '%s'", $clusterIdentifier));
        $progressBar = new ezcConsoleProgressbar( new ezcConsoleOutput(), count($rows), array(
            'emptyChar' => ' ',
            'barChar'   => '='
        ) );
        $progressBar->start();

        foreach($rows as $row)
        {
            if(!array_key_exists($clusterIdentifier, $config))
            {
                continue;
            }

            $fq = $config[$clusterIdentifier][$row["application_identifier"]]["filters"];

            $solrBase = new eZSolrBase();
            $params = array(
                'indent'       => 'on',
                'q'            => '"'.$row['keyword'].'"',
                'fq'           => $fq,
                'start'        => 0,
                'rows'         => 0,
                'fl'           => '',
                'qt'           => 'ezpublish',
                'explainOther' => '',
                'hl.fl'        => '',
            );

            $results = $solrBase->rawSolrRequest('/select', $params);
            $num_found = $results['response']['numFound'];
            $db->query(sprintf("UPDATE mm_seo SET nb_results=%d, speciality_url='%s', keyword_url='%s' WHERE id=%d",
                $num_found,
                self::sanitize($row["speciality"]),
                self::sanitize($row["keyword"]),
                $row["id"]));

            $progressBar->advance();
        }
        $progressBar->finish();
        $cli->output();
    }
예제 #8
0
function exitError($msg = false)
{
    $erroMsg = 'Newsletter image error ' . $_SERVER['REQUEST_URI'];
    if ($msg)
    {
        $erroMsg .= "\n$msg";
    }
    eZDebug::writeError( $erroMsg );
    header('HTTP/1.0 404 Not Found');
    eZExecution::cleanExit();
}
    public function contentBuildResult()
    {
        $errorCode = empty( $this->errorCode ) ? '500' : $this->errorCode;
        $errorCodeList = HttpTool::$statusReason;

        $errorCodeKey   = array_key_exists( $errorCode, $errorCodeList ) ? $errorCode : '500';
        $errorMsg       = $errorCode . ' ' . $errorCodeList[$errorCodeKey];

        header( "HTTP/1.1 $errorMsg" );
        header( "Status: $errorMsg" );
        echo "ERROR: $errorMsg";

        eZExecution::cleanExit();
    }
예제 #10
0
function exitWithInternalError( $errorText )
{
    header( $_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error' );
    //include_once( 'extension/ezjscore/classes/ezjscajaxcontent.php' );
    $contentType = ezjscAjaxContent::getHttpAccept();

    // set headers
    if ( $contentType === 'xml' )
        header('Content-Type: text/xml; charset=utf-8');
    else if ( $contentType === 'json' )
        header('Content-Type: text/javascript; charset=utf-8');

    echo ezjscAjaxContent::autoEncode( array( 'error_text' => $errorText, 'content' => '' ), $contentType );
    eZExecution::cleanExit();
}
 function modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters)
 {
     $redirectUri = $namedParameters['url'];
     // if $redirectUri is not starting with scheme://
     if (!preg_match('#^\\w+://#', $redirectUri)) {
         // path to eZ Publish index
         $indexDir = eZSys::indexDir();
         /* We need to make sure we have one
            and only one slash at the concatenation point
            between $indexDir and $redirectUri. */
         $redirectUri = rtrim($indexDir, '/') . '/' . ltrim($redirectUri, '/');
     }
     // Redirect to $redirectUri by returning status code 301 and exit.
     eZHTTPTool::redirect($redirectUri, array(), 301);
     eZExecution::cleanExit();
 }
 public function __construct($theClass = '', $name = '')
 {
     parent::__construct($theClass, $name);
     if (!self::$script instanceof eZScript) {
         self::$script = eZScript::instance(array('description' => "eZ Publish Test Runner\n\nsets up an eZ Publish testing environment\n", 'use-session' => false, 'use-modules' => true, 'use-extensions' => true));
         // Override INI override folder from settings/override to
         // tests/settings to not read local override settings
         $ini = eZINI::instance();
         $ini->setOverrideDirs(array(array('tests/settings', true)), 'override');
         $ini->loadCache();
         // Be sure to have clean content language data
         eZContentLanguage::expireCache();
         self::$script->startup();
         self::$script->initialize();
         // Avoids Fatal error: eZ Publish did not finish its request if die() is used.
         eZExecution::setCleanExit();
     }
 }
예제 #13
0
    /**
     * Returns the configured instance of an eZClusterFileHandlerInterface
     * See ClusteringSettings.FileHandler in file.ini
     *
     * @param string|bool $filename
     *        Optional filename the handler should be initialized with
     *
     * @return eZClusterFileHandlerInterface
     */
    static function instance( $filename = false )
    {
        if ( self::$isShutdownFunctionRegistered !== true )
        {
            eZExecution::addCleanupHandler( array( __CLASS__, 'cleanupGeneratingFiles' ) );
            self::$isShutdownFunctionRegistered = true;
        }

        if( $filename !== false )
        {
            $optionArray = array( 'iniFile'      => 'file.ini',
                                  'iniSection'   => 'ClusteringSettings',
                                  'iniVariable'  => 'FileHandler',
                                  'handlerParams'=> array( $filename ) );

            $options = new ezpExtensionOptions( $optionArray );

            $handler = eZExtension::getHandlerClass( $options );

            return $handler;
        }
        else
        {
            // return Filehandler from GLOBALS based on ini setting.
            if ( self::$globalHandler === null )
            {
                $optionArray = array( 'iniFile'      => 'file.ini',
                                      'iniSection'   => 'ClusteringSettings',
                                      'iniVariable'  => 'FileHandler' );

                $options = new ezpExtensionOptions( $optionArray );

                $handler = eZExtension::getHandlerClass( $options );

                self::$globalHandler = $handler;
            }
            else
                $handler = self::$globalHandler;

            return $handler;
        }
    }
예제 #14
0
/**
 * Passthrough file, and exit cleanly
*/
function downloadFile($filePath)
{
    if (!file_exists($filePath)) {
        header("HTTP/1.1 404 Not Found");
        eZExecution::cleanExit();
    }
    ob_clean();
    header("Pragma: public");
    header("Expires: 0");
    // set expiration time
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment; filename=" . basename($filePath));
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($filePath));
    ob_end_clean();
    @readfile($filePath);
    eZExecution::cleanExit();
}
 private function connect()
 {
     if (is_resource($this->ConnectionResource)) {
         eZDebug::writeError('No Connexion Resource available', __METHOD__);
         return false;
     }
     $ini = eZINI::instance('ezsi.ini');
     $host = $ini->variable('FTPSettings', 'Host');
     $port = $ini->variable('FTPSettings', 'Port');
     $timeout = $ini->variable('FTPSettings', 'Timeout');
     $login = $ini->variable('FTPSettings', 'Login');
     $password = $ini->variable('FTPSettings', 'Password');
     $destinationFolder = $ini->variable('FTPSettings', 'DestinationFolder');
     if ($cr = @ftp_connect($host, $port, $timeout) and ftp_login($cr, $login, $password)) {
         eZDebug::writeNotice('Connecting to FTP server', 'eZSIFTPFileHandler');
         $this->ConnectionResource = $cr;
         $GLOBALS['eZSIFTPFileHandler'] = $this;
         unset($cr);
         // creating basic stucture if does not exists
         // the directory does not exists
         if (!@ftp_chdir($this->ConnectionResource, $destinationFolder)) {
             // create it
             //if( !@ftp_mkdir( $this->ConnectionResource, 'si-blocks' ) )
             if (!$this->mkDir($destinationFolder)) {
                 eZDebug::writeError('Unable to create dir ' . $destinationFolder, __METHOD__);
             }
             // dir should exists now
             eZDebug::writeNotice('CWD : ' . ftp_pwd($this->ConnectionResource), __METHOD__);
             ftp_chdir($this->ConnectionResource, $destinationFolder);
         }
         // make sure the connection is closed at the
         // end of the script
         eZExecution::addCleanupHandler('eZSIFTPCloseConnexion');
         return true;
     } else {
         eZDebug::writeError('Unable to connect to FTP server', __METHOD__);
         return false;
     }
 }
예제 #16
0
    /**
     * Installs the default Exception handler
     *
     * @params Exception the exception
     * @return void
     */
    static public function defaultExceptionHandler( Exception $e )
    {
        if( PHP_SAPI != 'cli' )
        {
            header( 'HTTP/1.x 500 Internal Server Error' );
            header( 'Content-Type: text/html' );

            echo "An unexpected error has occurred. Please contact the webmaster.<br />";

            if( eZDebug::isDebugEnabled() )
            {
                echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();
            }
        }
        else
        {
            $cli = eZCLI::instance();
            $cli->error( "An unexpected error has occurred. Please contact the webmaster.");

            if( eZDebug::isDebugEnabled() )
            {
                $cli->error( $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
            }
        }

        eZLog::write( 'Unexpected error, the message was : ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(), 'error.log' );

        eZExecution::cleanup();
        eZExecution::setCleanExit();
        exit( 1 );
    }
예제 #17
0
 /**
  * Runs the shutdown process
  */
 protected function shutdown($reInitialize = true)
 {
     eZExecution::cleanup();
     eZExecution::setCleanExit();
     eZExpiryHandler::shutdown();
     if ($reInitialize) {
         $this->isInitialized = false;
     }
 }
예제 #18
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();
 }
예제 #19
0
파일: runtests.php 프로젝트: nfrp/ezpublish
    }
}
$cli = eZCLI::instance();
$script = eZScript::instance(array('description' => "eZ Publish Test Runner\n\n" . "sets up an eZ Publish testing environment" . "\n", 'use-session' => false, 'use-modules' => true, 'use-extensions' => true));
// Override INI override folder from settings/override to
// tests/settings to not read local override settings
$ini = eZINI::instance();
$ini->setOverrideDirs(array(array('tests/settings', true)), 'override');
$ini->loadCache();
// Be sure to have clean content language data
eZContentLanguage::expireCache();
$script->startup();
// $options = $script->getOptions();
$script->initialize();
// Avoids Fatal error: eZ Publish did not finish its request if die() is used.
eZExecution::setCleanExit();
$version = PHPUnit_Runner_Version::id();
if (version_compare($version, '3.5.0') == -1 && $version !== '@package_version@') {
    die("PHPUnit 3.5.0 (or later) is required to run this test suite.\n");
}
require_once 'PHP/CodeCoverage.php';
$codeCoverage = new PHP_CodeCoverage();
$codeCoverage->filter()->addFileToBlacklist(__FILE__, 'PHPUNIT');
//require_once 'bootstrap.php';
try {
    $runner = ezpTestRunner::instance();
    $runner->run($_SERVER['argv']);
} catch (Exception $e) {
    $cli->error($e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
    $cli->error($e->getTraceAsString());
}
<?php

/**
 * File containing the pixelate tool handler
 *
 * @copyright Copyright (C) eZ Systems AS.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version //autogentag//
 * @package ezie
 */
$prepare_action = new eZIEImagePreAction();
$http = eZHTTPTool::instance();
$region = null;
if ($prepare_action->hasRegion()) {
    $region = $prepare_action->getRegion();
}
// retrieve image dimensions
$analyzer = new eZIEImageAnalyzer($prepare_action->getImagePath());
$imageconverter = new eZIEezcImageConverter(eZIEImageToolPixelate::filter($analyzer->data->width, $analyzer->data->height, $region));
$imageconverter->perform($prepare_action->getImagePath(), $prepare_action->getNewImagePath());
eZIEImageToolResize::doThumb($prepare_action->getNewImagePath(), $prepare_action->getNewThumbnailPath());
echo (string) $prepare_action;
eZExecution::cleanExit();
예제 #21
0
}
$script->setUseDebugOutput($debugOutput);
$script->setAllowedDebugLevels($allowedDebugLevels);
$script->setUseDebugAccumulators($useDebugAccumulators);
$script->setUseDebugTimingPoints($useDebugTimingpoints);
$script->setUseIncludeFiles($useIncludeFiles);
$script->setIsQuiet($isQuiet);
if ($webOutput) {
    $useColors = true;
}
$cli->setUseStyles($useColors);
$script->setDebugMessage("\n\n" . str_repeat('#', 36) . $cli->style('emphasize') . " DEBUG " . $cli->style('emphasize-end') . str_repeat('#', 36) . "\n");
$script->setUseSiteAccess($siteaccess);
$script->initialize();
$cli->output("Updating content object names");
eZExecution::registerShutdownHandler();
$db = eZDB::instance();
if ($dbHost || $dbName || $dbUser || $dbImpl) {
    $params = array();
    if ($dbHost !== false) {
        $params['server'] = $dbHost;
    }
    if ($dbUser !== false) {
        $params['user'] = $dbUser;
        $params['password'] = '';
    }
    if ($dbPassword !== false) {
        $params['password'] = $dbPassword;
    }
    if ($dbName !== false) {
        $params['database'] = $dbName;
    /**
     * Handles redirection to the mobile optimized interface
     *
     */
    public function redirect()
    {
        $http = eZHTTPTool::instance();
        $currentSiteAccess = eZSiteAccess::current();

        if ( $http->hasGetVariable( 'notmobile' ) )
        {
            setcookie( 'eZMobileDeviceDetect', 1, time() + (int)eZINI::instance()->variable( 'SiteAccessSettings', 'MobileDeviceDetectCookieTimeout' ), '/' );

            $http->redirect( eZSys::indexDir() );

            eZExecution::cleanExit();
        }

        if ( !isset( $_COOKIE['eZMobileDeviceDetect'] )
                && !in_array( $currentSiteAccess['name'], eZINI::instance()->variable( 'SiteAccessSettings', 'MobileSiteAccessList'  ) ) )
        {
            $http->redirect( eZINI::instance()->variable( 'SiteAccessSettings', 'MobileSiteAccessURL' ) );

            eZExecution::cleanExit();
        }
    }
 static function checkUser(&$siteBasics, &$url)
 {
     $http = eZHTTPTool::instance();
     if (!$http->hasSessionVariable(self::STEP)) {
         $http->setSessionVariable(self::STEP, self::STEP_PRE_CHECK_USER_INFO);
     }
     $loginStep =& $http->sessionVariable(self::STEP);
     if ($http->hasSessionVariable(self::FORCE_LOGIN) && $loginStep < self::STEP_PRE_COLLECT_USER_INFO) {
         $loginStep = self::STEP_PRE_COLLECT_USER_INFO;
     }
     switch ($loginStep) {
         case self::STEP_PRE_CHECK_USER_INFO:
             $ini = eZINI::instance();
             $handlerList = array('standard');
             if ($ini->hasVariable('UserSettings', 'LoginHandler')) {
                 $handlerList = $ini->variable('UserSettings', 'LoginHandler');
             }
             if ($http->hasSessionVariable(self::LAST_HANDLER_NAME)) {
                 $http->removeSessionVariable(self::LAST_HANDLER_NAME);
             }
             foreach ($handlerList as $handler) {
                 $userObject = eZUserLoginHandler::instance($handler);
                 if ($userObject) {
                     $check = $userObject->checkUser($siteBasics, $url);
                     if ($check === null) {
                         eZUserLoginHandler::sessionCleanup();
                         return null;
                     }
                     $http->setSessionVariable(self::LAST_CHECK_REDIRECT, $check);
                     $http->setSessionVariable(self::LAST_HANDLER_NAME, $handler);
                 }
             }
             $http->setSessionVariable(self::STEP, self::STEP_PRE_COLLECT_USER_INFO);
             return eZUserLoginHandler::checkUser($siteBasics, $url);
             break;
         case self::STEP_PRE_COLLECT_USER_INFO:
             $http->setSessionVariable(self::STEP, self::STEP_POST_COLLECT_USER_INFO);
             $handler = null;
             if ($http->hasSessionVariable(self::LAST_HANDLER_NAME)) {
                 $handlerName = $http->sessionVariable(self::LAST_HANDLER_NAME);
                 $handler = eZUserLoginHandler::instance($handlerName);
             }
             if ($handler) {
                 return $handler->preCollectUserInfo();
             } else {
                 $redirect =& $http->sessionVariable(self::LAST_CHECK_REDIRECT);
                 if (!$redirect) {
                     $redirect = array('module' => 'user', 'function' => 'login');
                 }
                 return $redirect;
             }
             break;
         case self::STEP_POST_COLLECT_USER_INFO:
             $http->setSessionVariable(self::STEP, self::STEP_LOGIN_USER);
             $handler = null;
             if ($http->hasSessionVariable(self::LAST_HANDLER_NAME)) {
                 $handlerName = $http->sessionVariable(self::LAST_HANDLER_NAME);
                 $handler = eZUserLoginHandler::instance($handlerName);
             }
             if ($handler) {
                 // Use specified login handler to handle Login info input
                 if (!$handler->postCollectUserInfo()) {
                     eZUserLoginHandler::sessionCleanup();
                     eZHTTPTool::redirect('/');
                     eZExecution::cleanExit();
                 }
             }
             return eZUserLoginHandler::checkUser($siteBasics, $url);
             break;
         case self::STEP_LOGIN_USER:
             $ini = eZINI::instance();
             $handlerList = array('standard');
             if ($ini->hasVariable('UserSettings', 'LoginHandler')) {
                 $handlerList = $ini->variable('UserSettings', 'LoginHandler');
             }
             $userInfoArray =& $http->sessionVariable(self::USER_INFO);
             $http->removeSessionVariable(self::USER_INFO);
             if ($http->hasSessionVariable(self::FORCE_LOGIN)) {
                 $http->removeSessionVariable(self::FORCE_LOGIN);
             }
             $user = null;
             if (is_array($userInfoArray) and $userInfoArray['login'] and $userInfoArray['password']) {
                 foreach ($handlerList as $handler) {
                     $userObject = eZUserLoginHandler::instance($handler);
                     if ($userObject) {
                         $user = $userObject->loginUser($userInfoArray['login'], $userInfoArray['password']);
                         if (is_subclass_of($user, 'eZUser')) {
                             eZUserLoginHandler::sessionCleanup();
                             return null;
                         } else {
                             if (is_array($user)) {
                                 eZUserLoginHandler::sessionCleanup();
                                 return $user;
                             }
                         }
                     }
                 }
             }
             $http->setSessionVariable(self::STEP, self::STEP_PRE_CHECK_USER_INFO);
             return eZUserLoginHandler::checkUser($siteBasics, $url);
             break;
     }
 }
예제 #24
0
 /**
  * Registers the 'cleanup' function as shutdown handler, trying to do it only once
  *
  * @param bool $onlyIfConfigured when true, the registration only happens subject to an ini setting
  * @return bool false if registration is aborted, true if the handler is (or was already) registered
  */
 public static function registerShutdownPerfLogger($onlyIfConfigured = false, $eZ5Context = false)
 {
     if ($onlyIfConfigured && eZPerfLoggerINI::variable('GeneralSettings', 'AlwaysRegisterShutdownPerfLogger') !== 'enabled') {
         return false;
     }
     foreach (eZExecution::cleanupHandlers() as $handler) {
         if ($handler == array(__CLASS__, 'cleanup') || $handler == array(__CLASS__, 'cleanupOnCleanExit')) {
             return true;
         }
     }
     if ($eZ5Context) {
         eZExecution::addCleanupHandler(array(__CLASS__, 'cleanupOnCleanExit'));
     } else {
         eZExecution::addCleanupHandler(array(__CLASS__, 'cleanup'));
     }
     return true;
 }
예제 #25
0
 /**
  * Returns a shared instance of the eZUser class pr $id value.
  * If user can not be fetched, then anonymous user is returned and
  * a warning trown, if anonymous user can not be fetched, then NoUser
  * is returned and another warning is thrown.
  *
  * @param int|false $id On false: Gets current user id from session
  *        or from {@link eZUser::anonymousId()} if not set.
  * @return eZUser
  */
 static function instance($id = false)
 {
     if (!empty($GLOBALS["eZUserGlobalInstance_{$id}"])) {
         return $GLOBALS["eZUserGlobalInstance_{$id}"];
     }
     $userId = $id;
     $currentUser = null;
     $http = eZHTTPTool::instance();
     $anonymousUserID = self::anonymousId();
     $sessionHasStarted = eZSession::hasStarted();
     // If not specified get the current user
     if ($userId === false) {
         if ($sessionHasStarted) {
             $userId = $http->sessionVariable('eZUserLoggedInID');
             if (!is_numeric($userId)) {
                 $userId = $anonymousUserID;
                 eZSession::setUserID($userId);
                 $http->setSessionVariable('eZUserLoggedInID', $userId);
             }
         } else {
             $userId = $anonymousUserID;
             eZSession::setUserID($userId);
         }
     }
     // Check user cache (this effectivly fetches user from cache)
     // user not found if !isset( isset( $userCache['info'][$userId] ) )
     $userCache = self::getUserCacheByUserId($userId);
     if (isset($userCache['info'][$userId])) {
         $userArray = $userCache['info'][$userId];
         if (is_numeric($userArray['contentobject_id'])) {
             $currentUser = new eZUser($userArray);
             $currentUser->setUserCache($userCache);
         }
     }
     $ini = eZINI::instance();
     // Check if:
     // - the user has not logged out,
     // - the user is not logged in,
     // - and if a automatic single sign on plugin is enabled.
     if (!self::$userHasLoggedOut && is_object($currentUser) && !$currentUser->isRegistered()) {
         $ssoHandlerArray = $ini->variable('UserSettings', 'SingleSignOnHandlerArray');
         if (!empty($ssoHandlerArray)) {
             $ssoUser = false;
             foreach ($ssoHandlerArray as $ssoHandler) {
                 $className = 'eZ' . $ssoHandler . 'SSOHandler';
                 if (class_exists($className)) {
                     $impl = new $className();
                     $ssoUser = $impl->handleSSOLogin();
                     // If a user was found via SSO, then use it
                     if ($ssoUser !== false) {
                         $currentUser = $ssoUser;
                         $userId = $currentUser->attribute('contentobject_id');
                         $userInfo = array();
                         $userInfo[$userId] = array('contentobject_id' => $userId, 'login' => $currentUser->attribute('login'), 'email' => $currentUser->attribute('email'), 'password_hash' => $currentUser->attribute('password_hash'), 'password_hash_type' => $currentUser->attribute('password_hash_type'));
                         eZSession::setUserID($userId);
                         $http->setSessionVariable('eZUserLoggedInID', $userId);
                         eZUser::updateLastVisit($userId);
                         eZUser::setCurrentlyLoggedInUser($currentUser, $userId);
                         eZHTTPTool::redirect(eZSys::wwwDir() . eZSys::indexFile(false) . eZSys::requestURI() . eZSys::queryString(), array(), 302);
                         eZExecution::cleanExit();
                     }
                 } else {
                     eZDebug::writeError("Undefined ssoHandler class: {$className}", __METHOD__);
                 }
             }
         }
     }
     if ($userId != $anonymousUserID) {
         $sessionInactivityTimeout = $ini->variable('Session', 'ActivityTimeout');
         if (!isset($GLOBALS['eZSessionIdleTime'])) {
             eZUser::updateLastVisit($userId);
         } else {
             $sessionIdle = $GLOBALS['eZSessionIdleTime'];
             if ($sessionIdle > $sessionInactivityTimeout) {
                 eZUser::updateLastVisit($userId);
             }
         }
     }
     if (!$currentUser) {
         $currentUser = eZUser::fetch(self::anonymousId());
         eZDebug::writeWarning('User not found, returning anonymous');
     }
     if (!$currentUser) {
         $currentUser = new eZUser(array('id' => -1, 'login' => 'NoUser'));
         eZDebug::writeWarning('Anonymous user not found, returning NoUser');
     }
     $GLOBALS["eZUserGlobalInstance_{$id}"] = $currentUser;
     return $currentUser;
 }
예제 #26
0
function contentPDFPassthrough($cacheFile)
{
    $file = eZClusterFileHandler::instance($cacheFile);
    if (!$file->exists()) {
        eZDebug::writeError("Cache-file for pdf doesn't exist", 'content::pdf::contentPDFPassthrough');
        return;
    }
    $file->fetch(true);
    ob_clean();
    header('Pragma: ');
    header('Cache-Control: ');
    /* Set cache time out to 10 seconds, this should be good enough to work around an IE bug */
    header("Expires: " . gmdate('D, d M Y H:i:s', time() + 10) . ' GMT');
    header('X-Powered-By: ' . eZPublishSDK::EDITION);
    header('Content-Length: ' . $file->size());
    header('Content-Type: application/pdf');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    ob_end_clean();
    $fp = @fopen($cacheFile, 'r');
    @fpassthru($fp);
    fclose($fp);
    eZExecution::cleanExit();
}
예제 #27
0
 /**
  * output the pdf code, streaming it to the browser
  * the relevant headers are set so that hopefully the browser will recognise it
  */
 function stream($options = '')
 {
     // setting the options allows the adjustment of the headers
     // values at the moment are:
     // 'Content-Disposition'=>'filename'  - sets the filename, though not too sure how well this will
     //        work as in my trial the browser seems to use the filename of the php file with .pdf on the end
     // 'Accept-Ranges'=>1 or 0 - if this is not set to 1, then this header is not included, off by default
     //    this header seems to have caused some problems despite tha fact that it is supposed to solve
     //    them, so I am leaving it off by default.
     // 'compress'=> 1 or 0 - apply content stream compression, this is on (1) by default
     if (!is_array($options)) {
         $options = array();
     }
     if (isset($options['compress']) && $options['compress'] == 0) {
         $tmp = $this->output(1);
     } else {
         $tmp = $this->output();
     }
     $tmp = ltrim($tmp);
     ob_clean();
     header('Pragma: ');
     header('Cache-Control: ');
     /* Set cache time out to 10 seconds, this should be good enough to work around an IE bug */
     header("Expires: " . gmdate('D, d M Y H:i:s', time() + 10) . ' GMT');
     header('X-Powered-By: eZ Publish');
     header('Content-Length: ' . strlen($tmp));
     header('Content-Type: application/pdf');
     header('Content-Transfer-Encoding: binary');
     header('Accept-Ranges: bytes');
     ob_end_clean();
     echo $tmp;
     eZExecution::cleanExit();
 }
예제 #28
0
 static function download($file, $isAttachedDownload = true, $overrideFilename = false)
 {
     if (file_exists($file)) {
         $mimeinfo = eZMimeType::findByURL($file);
         ob_clean();
         header('X-Powered-By: eZ Publish');
         header('Content-Length: ' . filesize($file));
         header('Content-Type: ' . $mimeinfo['name']);
         // Fixes problems with IE when opening a file directly
         header("Pragma: ");
         header("Cache-Control: ");
         /* Set cache time out to 10 minutes, this should be good enough to work
            around an IE bug */
         header("Expires: " . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT');
         if ($overrideFilename) {
             $mimeinfo['filename'] = $overrideFilename;
         }
         if ($isAttachedDownload) {
             header('Content-Disposition: attachment; filename=' . $mimeinfo['filename']);
         } else {
             header('Content-Disposition: inline; filename=' . $mimeinfo['filename']);
         }
         header('Content-Transfer-Encoding: binary');
         header('Accept-Ranges: bytes');
         ob_end_clean();
         @readfile($file);
         eZExecution::cleanExit();
     } else {
         return false;
     }
 }
예제 #29
0
function exitWithInternalError()
{
    header( $_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error' );
    eZExecution::cleanup();
    eZExecution::setCleanExit();
}
예제 #30
0
/**
 * oAuth2 response handler function. Terminates execution after sending the headers.
 *
 * @param string $httpHeader The HTTP header to be sent as a response
 * @param string $location The location to redirect to. No redirection is done if not provided.
 *
 * @return void
 */
function response($httpHeader, $location = null)
{
    header("HTTP/1.1 {$httpHeader}");
    if ($location !== null) {
        // debug stuff: echo "header( \"Location: $location\" );\n";
        header("Location: {$location}");
    }
    eZExecution::cleanExit();
}