addCleanupHandler() static public method

The function is called at the end of the script execution to do some cleanups.
static public addCleanupHandler ( $handler )
コード例 #1
0
 public static function trackTransaction()
 {
     eZExecution::addCleanupHandler(function () {
         $newrelic = new Newrelic(true);
         $newrelic->nameTransaction(self::buildCurrentTransactionName());
     });
 }
コード例 #2
0
 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'));
     }
 }
コード例 #3
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;
        }
    }
コード例 #4
0
 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;
     }
 }
コード例 #5
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;
 }
コード例 #6
0
        $db->setIsSQLOutputEnabled(false);
    }
}
function eZFatalError()
{
    eZDebug::setHandleType(eZDebug::HANDLE_NONE);
    eZWebDAVContentBackend::appendLogEntry("****************************************");
    eZWebDAVContentBackend::appendLogEntry("Fatal error: eZ Publish did not finish its request");
    eZWebDAVContentBackend::appendLogEntry("The execution of eZ Publish was abruptly ended, the debug output is present below.");
    eZWebDAVContentBackend::appendLogEntry("****************************************");
    // $templateResult = null;
    // eZDisplayResult( $templateResult );
}
// Check and proceed only if WebDAV functionality is enabled:
if ($enable === 'true') {
    eZExecution::addCleanupHandler('eZDBCleanup');
    eZExecution::addFatalErrorHandler('eZFatalError');
    eZDebug::setHandleType(eZDebug::HANDLE_FROM_PHP);
    if (!isset($_SERVER['REQUEST_URI']) or !isset($_SERVER['REQUEST_METHOD'])) {
        // We stop the script if these are missing
        // e.g. if run from the shell
        eZExecution::cleanExit();
    }
    include_once "access.php";
    eZModule::setGlobalPathList(array("kernel"));
    eZWebDAVContentBackend::appendLogEntry("========================================");
    eZWebDAVContentBackend::appendLogEntry("Requested URI is: " . $_SERVER['REQUEST_URI'], 'webdav.php');
    $ini = eZINI::instance('site.ini');
    // Initialize/set the index file.
    eZSys::init('webdav.php', $ini->variable('SiteAccessSettings', 'ForceVirtualHost') === 'true');
    // @as 2009-03-04 - added cleaning up of the REQUEST_URI and HTTP_DESTINATION
コード例 #7
0
ファイル: ezscript.php プロジェクト: nlescure/ezpublish
 function initialize()
 {
     if (ob_get_length() != 0) {
         ob_end_clean();
     }
     $debugINI = eZINI::instance('debug.ini');
     eZDebugSetting::setDebugINI($debugINI);
     // Initialize text codec settings
     $this->updateTextCodecSettings();
     // Initialize debug settings
     $this->updateDebugSettings($this->UseDebugOutput);
     // Set the different permissions/settings.
     $ini = eZINI::instance();
     $iniFilePermission = $ini->variable('FileSettings', 'StorageFilePermissions');
     $iniDirPermission = $ini->variable('FileSettings', 'StorageDirPermissions');
     $iniVarDirectory = eZSys::cacheDirectory();
     eZCodePage::setPermissionSetting(array('file_permission' => octdec($iniFilePermission), 'dir_permission' => octdec($iniDirPermission), 'var_directory' => $iniVarDirectory));
     eZExecution::addCleanupHandler('eZDBCleanup');
     eZExecution::addFatalErrorHandler('eZFatalError');
     eZDebug::setHandleType(eZDebug::HANDLE_FROM_PHP);
     if ($this->UseExtensions) {
         // Check for extension
         eZExtension::activateExtensions('default');
         // Extension check end
     } else {
         if (!$this->isQuiet()) {
             $cli = eZCLI::instance();
             $cli->output("Notice: This script uses 'use-extensions' => false, meaning extension settings are not loaded!");
         }
     }
     $siteaccess = $this->SiteAccess;
     if ($siteaccess) {
         $access = array('name' => $siteaccess, 'type' => eZSiteAccess::TYPE_STATIC);
     } else {
         $ini = eZINI::instance();
         $siteaccess = $ini->variable('SiteSettings', 'DefaultAccess');
         $access = array('name' => $siteaccess, 'type' => eZSiteAccess::TYPE_DEFAULT);
     }
     $access = eZSiteAccess::change($access);
     if ($this->UseExtensions) {
         // Check for siteaccess extension
         eZExtension::activateExtensions('access');
         // Extension check end
     }
     // Now that all extensions are activated and siteaccess has been changed, reset
     // all eZINI instances as they may not take into account siteaccess specific settings.
     eZINI::resetAllInstances(false);
     // Set the global setting which is read by the session lib
     $GLOBALS['eZSiteBasics']['session-required'] = $this->UseSession;
     if ($this->UseSession) {
         $db = eZDB::instance();
         if ($db->isConnected()) {
             eZSession::start();
         } else {
             $this->setIsInitialized(false);
             $this->InitializationErrorMessage = 'database error: ' . $db->errorMessage();
             return;
         }
     }
     if ($this->User) {
         $userLogin = $this->User['login'];
         $userPassword = $this->User['password'];
         if ($userLogin and $userPassword) {
             $userID = eZUser::loginUser($userLogin, $userPassword);
             if (!$userID) {
                 $cli = eZCLI::instance();
                 if ($this->isLoud()) {
                     $cli->warning('Failed to login with user ' . $userLogin);
                 }
                 eZExecution::cleanup();
                 eZExecution::setCleanExit();
             }
         }
     }
     // Initialize module handling
     if ($this->UseModules) {
         $moduleRepositories = eZModule::activeModuleRepositories($this->UseExtensions);
         eZModule::setGlobalPathList($moduleRepositories);
     }
     $this->setIsInitialized(true);
 }
コード例 #8
0
 /**
  * Constructs an ezpKernel instance
  */
 public function __construct(array $settings = array())
 {
     $this->settings = $settings + array('siteaccess' => null, 'use-exceptions' => false, 'session' => null);
     unset($settings);
     require_once __DIR__ . '/global_functions.php';
     $this->setUseExceptions($this->settings['use-exceptions']);
     $GLOBALS['eZSiteBasics'] = array('external-css' => true, 'show-page-layout' => true, 'module-run-required' => true, 'policy-check-required' => true, 'policy-check-omit-list' => array(), 'url-translator-allowed' => true, 'validity-check-required' => false, 'user-object-required' => true, 'session-required' => true, 'db-required' => false, 'no-cache-adviced' => false, 'site-design-override' => false, 'module-repositories' => array());
     $this->siteBasics =& $GLOBALS['eZSiteBasics'];
     // Reads settings from i18n.ini and passes them to eZTextCodec.
     list($i18nSettings['internal-charset'], $i18nSettings['http-charset'], $i18nSettings['mbstring-extension']) = eZINI::instance('i18n.ini')->variableMulti('CharacterSettings', array('Charset', 'HTTPCharset', 'MBStringExtension'), array(false, false, 'enabled'));
     eZTextCodec::updateSettings($i18nSettings);
     // @todo Change so code only supports utf-8 in 5.0?
     // Initialize debug settings.
     eZUpdateDebugSettings();
     // Set the different permissions/settings.
     $ini = eZINI::instance();
     // Set correct site timezone
     $timezone = $ini->variable("TimeZoneSettings", "TimeZone");
     if ($timezone) {
         date_default_timezone_set($timezone);
     }
     list($iniFilePermission, $iniDirPermission) = $ini->variableMulti('FileSettings', array('StorageFilePermissions', 'StorageDirPermissions'));
     // OPTIMIZATION:
     // Sets permission array as global variable, this avoids the eZCodePage include
     $GLOBALS['EZCODEPAGEPERMISSIONS'] = array('file_permission' => octdec($iniFilePermission), 'dir_permission' => octdec($iniDirPermission), 'var_directory' => eZSys::cacheDirectory());
     unset($i18nSettings, $timezone, $iniFilePermission, $iniDirPermission);
     eZExecution::addCleanupHandler(function () {
         if (class_exists('eZDB', false) && eZDB::hasInstance()) {
             eZDB::instance()->setIsSQLOutputEnabled(false);
         }
     });
     eZExecution::addFatalErrorHandler(function () {
         header("HTTP/1.1 500 Internal Server Error");
         echo "<b>Fatal error</b>: The web server did not finish its request<br/>";
         if (ini_get('display_errors') == 1) {
             if (eZDebug::isDebugEnabled()) {
                 echo "<p>The execution of eZ Publish was abruptly ended, the debug output is present below.</p>";
             } else {
                 echo "<p>Debug information can be found in the log files normally placed in var/log/* or by enabling 'DebugOutput' in site.ini</p>";
             }
         } else {
             echo "<p>Contact website owner with current url and info on what you did, and owner will be able to debug the issue further (by enabling 'display_errors' in php.ini).</p>";
         }
         eZDisplayResult(null);
     });
     eZExecution::setCleanExit();
     // Enable this line to get eZINI debug output
     // eZINI::setIsDebugEnabled( true );
     // Enable this line to turn off ini caching
     // eZINI::setIsCacheEnabled( false);
     if ($ini->variable('RegionalSettings', 'Debug') === 'enabled') {
         eZLocale::setIsDebugEnabled(true);
     }
     eZDebug::setHandleType(eZDebug::HANDLE_FROM_PHP);
     $GLOBALS['eZGlobalRequestURI'] = eZSys::serverVariable('REQUEST_URI');
     // Initialize basic settings, such as vhless dirs and separators
     eZSys::init('index.php', $ini->variable('SiteAccessSettings', 'ForceVirtualHost') === 'true');
     // Check for extension
     eZExtension::activateExtensions('default');
     // Extension check end
     // Use injected siteaccess if available or match it internally.
     $this->access = isset($this->settings['siteaccess']) ? $this->settings['siteaccess'] : eZSiteAccess::match(eZURI::instance(eZSys::requestURI()), eZSys::hostname(), eZSys::serverPort(), eZSys::indexFile());
     eZSiteAccess::change($this->access);
     eZDebugSetting::writeDebug('kernel-siteaccess', $this->access, 'current siteaccess');
     // Check for siteaccess extension
     eZExtension::activateExtensions('access');
     // Siteaccess extension check end
     // Now that all extensions are activated and siteaccess has been changed, reset
     // all eZINI instances as they may not take into account siteaccess specific settings.
     eZINI::resetAllInstances(false);
     ezpEvent::getInstance()->registerEventListeners();
     $this->mobileDeviceDetect = new ezpMobileDeviceDetect(ezpMobileDeviceDetectFilter::getFilter());
     if ($this->mobileDeviceDetect->isEnabled()) {
         $this->mobileDeviceDetect->process();
         if ($this->mobileDeviceDetect->isMobileDevice()) {
             $this->mobileDeviceDetect->redirect();
         }
     }
     // eZSession::setSessionArray( $mainRequest->session );
     /**
      * Check for activating Debug by user ID (Final checking. The first was in eZDebug::updateSettings())
      * @uses eZUser::instance() So needs to be executed after eZSession::start()|lazyStart()
      */
     eZDebug::checkDebugByUser();
 }
コード例 #9
0
    $currentItem->setAttribute('status', SQLIImportItem::STATUS_FAILED);
    $currentItem->store();
    $aLastError = error_get_last();
    if ($aLastError) {
        SQLIImportLogger::logError($aLastError['message'] . ' at ' . $aLastError['file'] . ' (line ' . $aLastError['line'] . ')');
    }
    SQLIImportLogger::logError('An error has occurred during import process. The import status has been updated.');
    $script->shutdown(1);
}
eZExecution::addFatalErrorHandler('SQLIImportErrorCleanup');
// Registering Fatal Error handler
/**
 * Cleanup handler, in case of a non caught DB transaction error
 * @return void
 */
function SQLIImportCleanupHandler()
{
    // Check if an error has occurred and report it if necessary
    $db = eZDB::instance();
    if ($db->errorNumber() > 0) {
        SQLIImportToken::cleanAll();
        $factory = SQLIImportFactory::instance();
        $currentItem = $factory->getCurrentImportItem();
        $currentItem->setAttribute('status', SQLIImportItem::STATUS_FAILED);
        $currentItem->store();
        SQLIImportLogger::logError('A DB transaction error occurred : #' . $db->errorNumber() . ' - "' . $db->errorMessage() . '"');
        SQLIImportLogger::logError('An error has occurred during import process. The import status has been updated.');
    }
}
eZExecution::addCleanupHandler('SQLIImportCleanupHandler');
コード例 #10
0
 /**
  * Constructs an ezpKernel instance
  */
 public function __construct(array $settings = array())
 {
     if (isset($settings['injected-settings'])) {
         $injectedSettings = array();
         foreach ($settings['injected-settings'] as $keySetting => $injectedSetting) {
             list($file, $section, $setting) = explode('/', $keySetting);
             $injectedSettings[$file][$section][$setting] = $injectedSetting;
         }
         // Those settings override anything else in local .ini files and their overrides
         eZINI::injectSettings($injectedSettings);
     }
     if (isset($settings['injected-merge-settings'])) {
         $injectedSettings = array();
         foreach ($settings['injected-merge-settings'] as $keySetting => $injectedSetting) {
             list($file, $section, $setting) = explode('/', $keySetting);
             $injectedSettings[$file][$section][$setting] = $injectedSetting;
         }
         // Those settings override anything else in local .ini files and their overrides
         eZINI::injectMergeSettings($injectedSettings);
     }
     $this->settings = $settings + array('siteaccess' => null, 'use-exceptions' => false, 'session' => null, 'service-container' => null);
     unset($settings, $injectedSettings, $file, $section, $setting, $keySetting, $injectedSetting);
     require_once __DIR__ . '/global_functions.php';
     $this->setUseExceptions($this->settings['use-exceptions']);
     $GLOBALS['eZSiteBasics'] = array('external-css' => true, 'show-page-layout' => true, 'module-run-required' => true, 'policy-check-required' => true, 'policy-check-omit-list' => array(), 'url-translator-allowed' => true, 'validity-check-required' => false, 'user-object-required' => true, 'session-required' => true, 'db-required' => false, 'no-cache-adviced' => false, 'site-design-override' => false, 'module-repositories' => array());
     $this->siteBasics =& $GLOBALS['eZSiteBasics'];
     // Reads settings from i18n.ini and passes them to eZTextCodec.
     list($i18nSettings['internal-charset'], $i18nSettings['http-charset'], $i18nSettings['mbstring-extension']) = eZINI::instance('i18n.ini')->variableMulti('CharacterSettings', array('Charset', 'HTTPCharset', 'MBStringExtension'), array(false, false, 'enabled'));
     eZTextCodec::updateSettings($i18nSettings);
     // @todo Change so code only supports utf-8 in 5.0?
     // Initialize debug settings.
     eZUpdateDebugSettings();
     // Set the different permissions/settings.
     $ini = eZINI::instance();
     // Set correct site timezone
     $timezone = $ini->variable("TimeZoneSettings", "TimeZone");
     if ($timezone) {
         date_default_timezone_set($timezone);
     }
     list($iniFilePermission, $iniDirPermission) = $ini->variableMulti('FileSettings', array('StorageFilePermissions', 'StorageDirPermissions'));
     // OPTIMIZATION:
     // Sets permission array as global variable, this avoids the eZCodePage include
     $GLOBALS['EZCODEPAGEPERMISSIONS'] = array('file_permission' => octdec($iniFilePermission), 'dir_permission' => octdec($iniDirPermission), 'var_directory' => eZSys::cacheDirectory());
     unset($i18nSettings, $timezone, $iniFilePermission, $iniDirPermission);
     eZExecution::addCleanupHandler(function () {
         if (class_exists('eZDB', false) && eZDB::hasInstance()) {
             eZDB::instance()->setIsSQLOutputEnabled(false);
         }
     });
     // Sets up the FatalErrorHandler
     $this->setupFatalErrorHandler();
     // Enable this line to get eZINI debug output
     // eZINI::setIsDebugEnabled( true );
     // Enable this line to turn off ini caching
     // eZINI::setIsCacheEnabled( false);
     if ($ini->variable('RegionalSettings', 'Debug') === 'enabled') {
         eZLocale::setIsDebugEnabled(true);
     }
     eZDebug::setHandleType(eZDebug::HANDLE_FROM_PHP);
     $GLOBALS['eZGlobalRequestURI'] = eZSys::serverVariable('REQUEST_URI');
     // Initialize basic settings, such as vhless dirs and separators
     if ($this->hasServiceContainer() && $this->getServiceContainer()->has('request')) {
         eZSys::init(basename($this->getServiceContainer()->get('request')->server->get('SCRIPT_FILENAME')), $ini->variable('SiteAccessSettings', 'ForceVirtualHost') === 'true');
     } else {
         eZSys::init('index.php', $ini->variable('SiteAccessSettings', 'ForceVirtualHost') === 'true');
     }
     // Check for extension
     eZExtension::activateExtensions('default');
     // Extension check end
     // Use injected siteaccess if available or match it internally.
     $this->access = isset($this->settings['siteaccess']) ? $this->settings['siteaccess'] : eZSiteAccess::match(eZURI::instance(eZSys::requestURI()), eZSys::hostname(), eZSys::serverPort(), eZSys::indexFile());
     eZSiteAccess::change($this->access);
     eZDebugSetting::writeDebug('kernel-siteaccess', $this->access, 'current siteaccess');
     // Check for siteaccess extension
     eZExtension::activateExtensions('access');
     // Siteaccess extension check end
     // Now that all extensions are activated and siteaccess has been changed, reset
     // all eZINI instances as they may not take into account siteaccess specific settings.
     eZINI::resetAllInstances(false);
     ezpEvent::getInstance()->registerEventListeners();
     $this->mobileDeviceDetect = new ezpMobileDeviceDetect(ezpMobileDeviceDetectFilter::getFilter());
     // eZSession::setSessionArray( $mainRequest->session );
 }