public function __construct($type, $existingState = '') { pb_backupbuddy::status('details', 'Constructing rollback class.'); if ('rollback' != $type && 'restore' != $type) { $this->_error('Invalid restore type `' . htmlentities($type) . '`.'); return false; } register_shutdown_function(array(&$this, 'shutdown_function')); pb_backupbuddy::status('details', 'Setting restore state defaults.'); $this->_state = array('type' => $type, 'archive' => '', 'serial' => '', 'tempPath' => '', 'data' => array(), 'undoURL' => '', 'forceMysqlMethods' => array(), 'autoAdvance' => true, 'maxExecutionTime' => backupbuddy_core::detectMaxExecutionTime(), 'dbImportPoint' => 0, 'zipMethodStrategy' => 'all', 'restoreFiles' => true, 'restoreDatabase' => true, 'migrateHtaccess' => true, 'databaseSettings' => array('server' => '', 'database' => '', 'username' => '', 'password' => '', 'prefix' => '', 'tempPrefix' => '', 'wipePrefix' => false, 'renamePrefix' => false, 'wipeDatabase' => false, 'ignoreSqlErrors' => false, 'sqlFiles' => array(), 'sqlFilesLocation' => '', 'databaseMethodStrategy' => 'php', 'importResumePoint' => '', 'importedResumeRows' => 0, 'importedResumeFails' => 0, 'importedResumeTime' => 0, 'migrateDatabase' => true, 'migrateDatabaseBruteForce' => true, 'migrateResumeSteps' => '', 'migrateResumePoint' => ''), 'cleanup' => array('deleteArchive' => true, 'deleteTempFiles' => true, 'deleteImportBuddy' => true, 'deleteImportLog' => true), 'potentialProblems' => array(), 'stepHistory' => array()); // Restore-specific default options. if ('restore' == $type) { $this->_state['skipUnzip'] = false; $this->_state['restoreFiles'] = true; $this->_state['restoreDatabase'] = true; $this->_state['migrateHtaccess'] = true; $this->_state['tempPath'] = ABSPATH . 'importbuddy/temp_' . pb_backupbuddy::$options['log_serial'] . '/'; } elseif ('rollback' == $type) { $this->_state['tempPath'] = backupbuddy_core::getTempDirectory() . $this->_state['type'] . '_' . $this->_state['serial'] . '/'; } if (is_array($existingState)) { // User passed along an existing state to resume. pb_backupbuddy::status('details', 'Using provided restore state data.'); $this->_state = $this->_array_replace_recursive($this->_state, $existingState); } // Check if a default state override exists. Used by automated restoring. /* if ( isset( pb_backupbuddy::$options['default_state_overrides'] ) && ( count( pb_backupbuddy::$options['default_state_overrides'] ) > 0 ) ) { // Default state overrides exist. Apply them. $this->_state = array_merge( $this->_state, pb_backupbuddy::$options['default_state_overrides'] ); } */ pb_backupbuddy::status('details', 'Restore class constructed in `' . $type . '` mode.'); pb_backupbuddy::set_greedy_script_limits(); // Just always assume we need this during restores/rollback... }
/** * Configures PHP error handling. * @return void */ public static function setupErrors() { error_reporting(E_ALL | E_STRICT); ini_set('display_errors', TRUE); ini_set('html_errors', FALSE); ini_set('log_errors', FALSE); set_exception_handler(array(__CLASS__, 'handleException')); set_error_handler(function ($severity, $message, $file, $line) { if (in_array($severity, array(E_RECOVERABLE_ERROR, E_USER_ERROR), TRUE) || ($severity & error_reporting()) === $severity) { Environment::handleException(new \ErrorException($message, 0, $severity, $file, $line)); } return FALSE; }); register_shutdown_function(function () { Assert::$onFailure = array(__CLASS__, 'handleException'); // note that Runner is unable to catch this errors in CLI & PHP 5.4.0 - 5.4.6 due PHP bug #62725 $error = error_get_last(); register_shutdown_function(function () use($error) { if (in_array($error['type'], array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE), TRUE)) { if (($error['type'] & error_reporting()) !== $error['type']) { // show fatal errors hidden by @shutup echo "\nFatal error: {$error['message']} in {$error['file']} on line {$error['line']}\n"; } } elseif (Environment::$checkAssertions && !Assert::$counter) { echo "\nError: This test forgets to execute an assertion.\n"; exit(Runner\Job::CODE_FAIL); } }); }); }
public function registerFatalHandler($level = null, $reservedMemorySize = 20) { register_shutdown_function(array($this, 'handleFatalError')); $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); $this->fatalLevel = $level; $this->hasFatalErrorHandler = true; }
/** * Constructor * * @param KObjectConfig $config An optional ObjectConfig object with configuration options */ public function __construct(KObjectConfig $config) { parent::__construct($config); //Session write and close handlers are called after destructing objects since PHP 5.0.5. if (version_compare(phpversion(), '5.4.0', '>=')) { session_register_shutdown(); } else { register_shutdown_function('session_write_close'); } //Only configure the session if it's not active yet if (!$this->isActive()) { //Set the session options $this->setOptions($config->options); //Set the session name if (!empty($config->name)) { $this->setName($config->name); } //Set the session identifier if (!empty($config->id)) { $this->setId($config->id); } //Set the session handler $this->setHandler($config->handler, KObjectConfig::unbox($config)); } //Set the session namespace $this->setNamespace($config->namespace); //Set lifetime time $this->getContainer('metadata')->setLifetime($config->lifetime); }
public static function setup($client_id, $client_secret, $podio_username, $podio_password, $options = array('session_manager' => null, 'curl_options' => array())) { // Setup client info self::$client_id = $client_id; self::$client_secret = $client_secret; // Setup curl self::$url = empty($options['api_url']) ? 'https://api.podio.com:443' : $options['api_url']; self::$debug = self::$debug ? self::$debug : false; self::$ch = curl_init(); self::$headers = array('Accept' => 'application/json'); curl_setopt(self::$ch, CURLOPT_RETURNTRANSFER, true); curl_setopt(self::$ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt(self::$ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt(self::$ch, CURLOPT_USERAGENT, 'Podio PHP Client/' . self::VERSION); curl_setopt(self::$ch, CURLOPT_HEADER, true); curl_setopt(self::$ch, CURLINFO_HEADER_OUT, true); if ($options && !empty($options['curl_options'])) { curl_setopt_array(self::$ch, $options['curl_options']); } if (!Cache::has('podio_oauth')) { self::authenticate_with_password($podio_username, $podio_password); Cache::put('podio_oauth', Podio::$oauth, 480); self::$oauth = Cache::get('podio_oauth'); } // Register shutdown function for debugging and session management register_shutdown_function('Podio::shutdown'); }
function __construct($locator) { $this->database = $locator->get('database'); $this->request = $locator->get('request'); $this->config = $locator->get('config'); register_shutdown_function(array($this, 'save_session')); $this->expire = $this->config->get('config_session_expire') > 1800 ? $this->config->get('config_session_expire') : 1800; if (!$this->request->has('alegro', 'cookie') && $this->request->isPost()) { $this->log_access(); if (strtolower(@$_SERVER['HTTP_CONNECTION']) == 'keep-alive') { echo $this->close_connection(); exit; } if ($this->check_access()) { echo $this->close_connection(); exit; } } if (!$this->request->has('alegro', 'cookie')) { setcookie('alegro', 'accept', time() + 60 * 60 * 24 * 30, '/', NULL, false); } if ($this->request->has('alegro', 'cookie')) { $this->start_session(); } }
/** * 処理の読み込みを行う * * @return void */ public static function load() { // E_DEPRECATED 定数 (for PHP < 5.3) // TODO バージョン互換処理に統合したい。 if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 8192); } // エラーレベル設定 (PHPのログに対する指定であり、以降のエラーハンドリングには影響しない模様) // 開発時は -1 (全て) を推奨 error_reporting(E_ALL & ~E_NOTICE & ~E_USER_NOTICE & ~E_DEPRECATED & ~E_STRICT); if (!(defined('SAFE') && SAFE === true) && !(defined('INSTALL_FUNCTION') && INSTALL_FUNCTION === true)) { // E_USER_ERROR または警告を捕捉した場合のエラーハンドラ set_error_handler(array(__CLASS__, 'handle_warning'), E_USER_ERROR | E_WARNING | E_USER_WARNING | E_CORE_WARNING | E_COMPILE_WARNING); // 実質的に PHP 5.2 以降かで処理が分かれる if (function_exists('error_get_last')) { // E_USER_ERROR 以外のエラーを捕捉した場合の処理用 register_shutdown_function(array(__CLASS__, 'handle_error')); // 以降の処理では画面へのエラー表示は行なわない ini_set('display_errors', 0); } else { // エラー捕捉用の出力バッファリング ob_start(array(__CLASS__, '_fatal_error_handler')); ini_set('display_errors', 1); } } }
function runRecache() { $app = JFactory::getApplication(); $params = JComponentHelper::getParams("com_jotcache"); $timeout = (int) $params->get('recachetimeout', 300); register_shutdown_function(array($this, 'recacheShutdown')); ini_set('max_execution_time', $timeout); $scopeAllow = array('none', 'chck', 'sel', 'all', 'direct'); $scope = $app->input->getWord('scope', ''); if (in_array($scope, $scopeAllow, TRUE)) { $this->_sql = $this->_db->getQuery(true); switch ($scope) { case 'none': return; case 'chck': $this->checkedRecache(); break; case 'sel': $this->selectedRecache($app); break; default: break; } if ($scope != 'direct') { $this->_sql->update($this->_db->quoteName('#__jotcache'))->set($this->_db->quoteName('recache') . ' = ' . $this->_db->quote(1)); $sql = $this->_db->setQuery($this->_sql); $sql->query(); } $this->controlRecache(1); define('JOTCACHE_RECACHE_BROWSER', true); $this->executeRunner($app); } $this->stopped = false; }
/** * Constructor * * @access protected * @param string $storage * @param array $options optional parameters */ function __construct($store = 'none', $options = array()) { // Register faked "destructor" in PHP4, this needs to happen before creating the session store if (version_compare(PHP_VERSION, '5') == -1) { register_shutdown_function(array(&$this, '__destruct')); } //Need to destroy any existing sessions started with session.auto_start if (session_id()) { session_unset(); session_destroy(); } //set default sessios save handler ini_set('session.save_handler', 'files'); //disable transparent sid support ini_set('session.use_trans_sid', '0'); //create handler $this->_store =& JSessionStorage::getInstance($store, $options); //set options $this->_setOptions($options); $this->_setCookieParams(); //load the session $this->_start(); //initialise the session $this->_setCounter(); $this->_setTimers(); $this->_state = 'active'; // perform security checks $this->_validate(); }
/** * Module bootstrap. */ public function onBootstrap($e) { $sm = $e->getApplication()->getServiceManager(); $options = $sm->get('loslog_options'); if ($options->getUseErrorLogger()) { $logger = $sm->get('LosLog\\Log\\ErrorLogger'); $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, [$logger, 'dispatchError'], -100); } if ($options->getUseSqlLogger()) { $em = $sm->get('doctrine.entitymanager.orm_default'); $sqlLogger = $sm->get('LosLog\\Log\\SqlLogger'); $sqlLogger->addLoggerTo($em); } if ($options->getUseRollbarLogger()) { $rollbar = $sm->get('RollbarNotifier'); if ($options->getExceptionhandler()) { set_exception_handler(array($rollbar, 'report_exception')); $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach('dispatch.error', function (Event $event) use($rollbar) { $exception = $event->getResult()->exception; if ($exception) { $rollbar->report_exception($exception); } }); } if ($options->getErrorhandler()) { set_error_handler(array($rollbar, 'report_php_error')); } if ($options->getShutdownfunction()) { register_shutdown_function($this->shutdownHandler($rollbar)); } } }
/** * Registers an error handler for PHP errors. * * @param Logger $logger * @param bool $continueNativeHandler * * @return bool Returna always false to enable other handlers, including the default * * @throws Exception\InvalidArgumentException if logger is null */ public static function registerErrorHandler(Logger $logger, $continueNativeHandler = false) { // Only register once per instance if (self::$registeredErrorHandler) { return false; } if ($logger === null) { throw new \Zend\Log\Exception\InvalidArgumentException('Invalid Logger specified'); } $errorHandlerMap = [E_NOTICE => self::NOTICE, E_USER_NOTICE => self::NOTICE, E_WARNING => self::WARN, E_CORE_WARNING => self::WARN, E_USER_WARNING => self::WARN, E_ERROR => self::ERR, E_USER_ERROR => self::ERR, E_CORE_ERROR => self::ERR, E_RECOVERABLE_ERROR => self::ERR, E_STRICT => self::DEBUG, E_DEPRECATED => self::DEBUG, E_USER_DEPRECATED => self::DEBUG]; $previous = set_error_handler(function ($errno, $errstr, $errfile, $errline) use($errorHandlerMap, $logger, $continueNativeHandler) { $errorLevel = error_reporting(); if ($errorLevel && $errno) { if (isset($errorHandlerMap[$errno])) { $priority = $errorHandlerMap[$errno]; } else { $priority = \Zend\Log\Logger::INFO; } $logger->log($priority, 'Error: ' . $errstr . ' in ' . $errfile . ' in line ' . $errline); return !$continueNativeHandler; } }); register_shutdown_function(function () use($logger) { $error = error_get_last(); if (null === $error) { return false; } $priority = \Zend\Log\Logger::ERR; $logger->log($priority, 'Error: ' . $error['message'] . ' in ' . $error['file'] . ' in line ' . $error['line']); }); self::$registeredErrorHandler = true; return $previous; }
function __construct($dbuser, $dbpassword, $dbname, $dbhost) { register_shutdown_function(array(&$this, "__destruct")); if ( defined('WP_DEBUG') and WP_DEBUG == true ) $this->show_errors(); if ( defined('DB_CHARSET') ) $this->charset = DB_CHARSET; if ( defined('DB_COLLATE') ) $this->collate = DB_COLLATE; $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true); if (!$this->dbh) { $this->bail(" <h1>Error establishing a database connection</h1> <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>$dbhost</code>. This could mean your host's database server is down.</p> <ul> <li>Are you sure you have the correct username and password?</li> <li>Are you sure that you have typed the correct hostname?</li> <li>Are you sure that the database server is running?</li> </ul> <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p> "); return; } $this->ready = true; if ( !empty($this->charset) && version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') ) $this->query("SET NAMES '$this->charset'"); $this->select($dbname); }
/** * PHP5 Constructor * Init the Database Abstraction layer */ public function __construct() { global $wpdb; register_shutdown_function(array($this, '__destruct')); /** * Taxonomy name * * @var string */ $this->taxonomy_name = 'avhec_catgroup'; $this->db_options_widget_titles = 'avhec_widget_titles'; // add DB pointer $wpdb->avhec_cat_group = $wpdb->prefix . 'avhec_category_groups'; /** * Create the table if it doesn't exist. */ if ($wpdb->get_var('show tables like \'' . $wpdb->avhec_cat_group . '\'') != $wpdb->avhec_cat_group) { add_action('init', array($this, 'doCreateTable'), 2); // Priority needs to be the same as the Register Taxonomy } add_action('init', array($this, 'doRegisterTaxonomy'), 2); // Priority for registering custom taxonomies is +1 over the creation of the initial taxonomies add_action('init', array($this, 'doSetupOptions')); add_action('admin_init', array($this, 'addMetaBoxes')); }
function PostNotify($pagename, &$page, &$new) { global $IsPagePosted; if ($IsPagePosted) { register_shutdown_function('NotifyUpdate', $pagename, getcwd()); } }
function createFile($imgURL) { $remImgURL = urldecode($imgURL); $urlParced = pathinfo($remImgURL); $remImgURLFilename = $urlParced['basename']; $imgData = wp_remote_get($remImgURL); if (is_wp_error($imgData)) { $badOut['Error'] = print_r($imgData, true) . " - ERROR"; return $badOut; } $imgData = $imgData['body']; $tmp = array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()] = tmpfile()))); if (!is_writable($tmp)) { return "Your temporary folder or file (file - " . $tmp . ") is not witable. Can't upload images to Flickr"; } rename($tmp, $tmp .= '.png'); register_shutdown_function(create_function('', "unlink('{$tmp}');")); file_put_contents($tmp, $imgData); if (!$tmp) { return 'You must specify a path to a file'; } if (!file_exists($tmp)) { return 'File path specified does not exist'; } if (!is_readable($tmp)) { return 'File path specified is not readable'; } // $data['name'] = basename($tmp); return "@{$tmp}"; }
/** * セッションの初期化を行う. * */ public function initSession() { session_set_save_handler(array(&$this, 'sfSessOpen'), array(&$this, 'sfSessClose'), array(&$this, 'sfSessRead'), array(&$this, 'sfSessWrite'), array(&$this, 'sfSessDestroy'), array(&$this, 'sfSessGc')); // 通常よりも早い段階(オブジェクトが破棄される前)でセッションデータを書き込んでセッションを終了する // XXX APC による MDB2 の破棄タイミングによる不具合を回避する目的 register_shutdown_function('session_write_close'); }
/** * Class constructor. * * @see initialize() */ public function __construct(sfEventDispatcher $dispatcher, $options = array()) { $this->initialize($dispatcher, $options); if (!isset($options['auto_shutdown']) || $options['auto_shutdown']) { register_shutdown_function(array($this, 'shutdown')); } }
/** * On first session instance creation, sets up the driver and creates session. */ public function __construct() { $this->input = Input::instance(); // This part only needs to be run once if (self::$instance === NULL) { // Load config self::$config = Kohana::config('session'); // Makes a mirrored array, eg: foo=foo self::$protect = array_combine(self::$protect, self::$protect); // Configure garbage collection ini_set('session.gc_probability', (int) self::$config['gc_probability']); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', self::$config['expiration'] == 0 ? 86400 : self::$config['expiration']); // Create a new session $this->create(); if (self::$config['regenerate'] > 0 and $_SESSION['total_hits'] % self::$config['regenerate'] === 0) { // Regenerate session id and update session cookie $this->regenerate(); } else { // Always update session cookie to keep the session alive cookie::set(self::$config['name'], $_SESSION['session_id'], self::$config['expiration']); } // Close the session just before sending the headers, so that // the session cookie(s) can be written. Event::add('system.send_headers', array($this, 'write_close')); // Make sure that sessions are closed before exiting register_shutdown_function(array($this, 'write_close')); // Singleton instance self::$instance = $this; } Kohana::log('debug', 'Session Library initialized'); }
public static function Factory(&$source, $conf_file = NULL, $conf_section = NULL, $strict = TRUE) { if (!is_array($source)) { user_error('$source ' . $source . ' is not an array', E_USER_NOTICE); } $cage = new Inspekt_Cage_Session(); $cage->_setSource($source); $cage->_parseAndApplyAutoFilters($conf_file); if (ini_get('session.use_cookies') || ini_get('session.use_only_cookies')) { if (isset($_COOKIE) && isset($_COOKIE[session_name()])) { session_id($_COOKIE[session_name()]); } elseif ($cookie = Inspekt::makeSessionCage()) { session_id($cookie->getAlnum(session_name())); } } else { // we're using session ids passed via GET if (isset($_GET) && isset($_GET[session_name()])) { session_id($_GET[session_name()]); } elseif ($cookie = Inspekt::makeSessionCage()) { session_id($cookie->getAlnum(session_name())); } } if ($strict) { $source = NULL; } return $cage; register_shutdown_function(); register_shutdown_function(array($this, '_repopulateSession')); }
/** * {@inheritdoc} */ public function handle(array $record) { if ($record['level'] < $this->level) { return false; } if (!$this->initialized) { // __destructor() doesn't get called on Fatal errors register_shutdown_function(array($this, 'close')); $this->initialized = true; } if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) { if ($this->flushOnOverflow) { $this->flush(); } else { array_shift($this->buffer); $this->bufferSize--; } } if ($this->processors) { foreach ($this->processors as $processor) { $record = call_user_func($processor, $record); } } $this->buffer[] = $record; $this->bufferSize++; return false === $this->bubble; }
/** * Constructor. Perform some checks about the OS and setserial * * @return phpSerial */ function Serial() { setlocale(LC_ALL, "en_US"); $sysname = php_uname(); if (substr($sysname, 0, 5) === "Linux") { $this->_os = "linux"; if ($this->_exec("stty --version") === 0) { register_shutdown_function(array($this, "deviceClose")); } else { trigger_error("No stty availible, unable to run.", E_USER_ERROR); } } elseif (substr($sysname, 0, 6) === "Darwin") { $this->_os = "osx"; // We know stty is available in Darwin. // stty returns 1 when run from php, because "stty: stdin isn't a // terminal" // skip this check // if($this->_exec("stty") === 0) // { register_shutdown_function(array($this, "deviceClose")); // } // else // { // trigger_error("No stty availible, unable to run.", E_USER_ERROR); // } } elseif (substr($sysname, 0, 7) === "Windows") { $this->_os = "windows"; register_shutdown_function(array($this, "deviceClose")); } else { trigger_error("Host OS is neither osx, linux nor windows, unable tu run.", E_USER_ERROR); exit; } }
public static function bootstrap($dispatch = true) { spl_autoload_register(array('Core', 'autoload')); if ($dispatch) { register_shutdown_function(array('Core', 'shutdown')); } }
/** * Checks if track ticket #$ticket_id is resolved * * @return bool|null true if the ticket is resolved, false if not resolved, null on error */ public static function isTracTicketClosed($trac_url, $ticket_id) { if (!extension_loaded('openssl')) { $trac_url = preg_replace("/^https:/", "http:", $trac_url); } if (!isset(self::$trac_ticket_cache[$trac_url])) { // In case you're running the tests offline, keep track of open tickets. $file = DIR_TESTDATA . '/.trac-ticket-cache.' . str_replace(array('http://', 'https://', '/'), array('', '', '-'), rtrim($trac_url, '/')); $tickets = @file_get_contents($trac_url . '/query?status=%21closed&format=csv&col=id'); // Check if our HTTP request failed. if (false === $tickets) { if (file_exists($file)) { register_shutdown_function(array('TracTickets', 'usingLocalCache')); $tickets = file_get_contents($file); } else { register_shutdown_function(array('TracTickets', 'forcingKnownBugs')); self::$trac_ticket_cache[$trac_url] = array(); return true; // Assume the ticket is closed, which means it gets run. } } else { $tickets = substr($tickets, 2); // remove 'id' column header $tickets = trim($tickets); file_put_contents($file, $tickets); } $tickets = explode("\r\n", $tickets); self::$trac_ticket_cache[$trac_url] = $tickets; } return !in_array($ticket_id, self::$trac_ticket_cache[$trac_url]); }
public function _updateCacheFileAfterExecution($environment = null) { static $called = false, $_environment; if ($called == false && !AkDbSchemaCache::shouldRefresh()) { register_shutdown_function(array('AkDbSchemaCache', '_updateCacheFileAfterExecution')); $called = !empty($environment) ? $environment : AK_ENVIRONMENT; } elseif (empty($environment)) { $config = AkDbSchemaCache::_config(null, null, $called); $file_name = AkDbSchemaCache::getCacheFileName($called); /** * @todo On PHP5 var_export requires objects that implement the __set_state magic method. * As see on stangelanda at arrowquick dot benchmarks at comhttp://php.net/var_export * serialize works faster without opcode caches. We should do our benchmarks with * var_export VS serialize using APC once we fix the __set_state magic on phpAdoDB */ if (AK_LOG_EVENTS) { $Logger =& Ak::getLogger(); } if (!AK_CLI) { if (AK_LOG_EVENTS) { $Logger->message('Updating database settings on ' . $file_name); } Ak::file_put_contents($file_name, serialize($config)); } else { if (AK_LOG_EVENTS) { $Logger->message('Skipping writing of cache file: ' . $file_name); } } } }
public function __construct($config, $options) { parent::__construct($config, $options); // Set default path for PhantomJS to "vendor/bin/phantomjs" for if it was installed via composer if (!isset($this->config['path'])) { $this->config['path'] = "vendor/bin/phantomjs"; } // If a directory was provided for the path, use old method of appending PhantomJS if (is_dir(realpath($this->config['path']))) { // Show warning that this is being deprecated $this->writeln("\r\n"); $this->writeln("WARNING: The PhantomJS path for Phantoman is set to a directory, this is being deprecated in the future. Please update your Phantoman configuration to be the full path to PhantomJS."); $this->config['path'] .= '/phantomjs'; } // Add .exe extension if running on the windows if ($this->isWindows() && file_exists(realpath($this->config['path'] . '.exe'))) { $this->config['path'] .= '.exe'; } // Set default WebDriver port if (!isset($this->config['port'])) { $this->config['port'] = 4444; } // Set default debug mode if (!isset($this->config['debug'])) { $this->config['debug'] = false; } $this->startServer(); $resource = $this->resource; register_shutdown_function(function () use($resource) { if (is_resource($resource)) { proc_terminate($resource); } }); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; declare (ticks=1); register_shutdown_function(array($this, 'stopCommand')); set_error_handler(array($this, 'errorHandler')); if (function_exists("pcntl_signal")) { pcntl_signal(SIGTERM, [$this, 'stopCommand']); pcntl_signal(SIGINT, [$this, 'stopCommand']); } else { } $this->isDebug = $input->getArgument('isDebug'); $port = $input->getOption('port'); $chat = $this->container->get('app.chat.handler'); $chat->setIsDebug($this->isDebug); $messageManager = new MessageManager($chat); $messageManager->setIsDebug($this->isDebug); $server = IoServer::factory(new HttpServer(new WsServer($messageManager)), $port); if ($this->isDebug) { $redis = $this->container->get('snc_redis.default'); $server->loop->addPeriodicTimer(5, function () use($redis, $messageManager) { $memory = memory_get_usage(); echo "Send messages. Redis value: " . $redis->get('value') . "\r\n"; $info = array(); $info['message'] = "Redis value: " . $redis->get('value') . "; Memory: " . $memory; $info['type'] = 'message'; $info['from'] = 'me'; $messageManager->sendAll(json_encode($info)); }); } $this->logMessage("Start server."); $server->run(); $this->logMessage("Finish execute daemon."); }
public function export_csv($page = 1) { set_time_limit(0); $limit = ($page - 1) * intval(app_conf("BATCH_PAGE_SIZE")) . "," . intval(app_conf("BATCH_PAGE_SIZE")); $map['ecv_type_id'] = intval($_REQUEST['ecv_type_id']); $list = M(MODULE_NAME)->where($map)->limit($limit)->findAll(); if ($list) { register_shutdown_function(array(&$this, 'export_csv'), $page + 1); $ecv_value = array('sn' => '""', 'password' => '""', 'money' => '""', 'use_limit' => '""', 'begin_time' => '""', 'end_time' => '""'); if ($page == 1) { $content = iconv("utf-8", "gbk", "序列号,密码,面额,使用数量,生效时间,过期时间"); $content = $content . "\n"; } foreach ($list as $k => $v) { $ecv_value['sn'] = '"' . iconv('utf-8', 'gbk', $v['sn']) . '"'; $ecv_value['password'] = '******' . iconv('utf-8', 'gbk', $v['password']) . '"'; $ecv_value['money'] = '"' . iconv('utf-8', 'gbk', format_price($v['money'])) . '"'; $ecv_value['use_limit'] = '"' . iconv('utf-8', 'gbk', $v['use_limit']) . '"'; $ecv_value['begin_time'] = '"' . iconv('utf-8', 'gbk', to_date($v['begin_time'])) . '"'; $ecv_value['end_time'] = '"' . iconv('utf-8', 'gbk', to_date($v['end_time'])) . '"'; $content .= implode(",", $ecv_value) . "\n"; } header("Content-Disposition: attachment; filename=voucher_list.csv"); echo $content; } else { if ($page == 1) { $this->error(L("NO_RESULT")); } } }
/** @internal */ public function __testbench_database_setup($connection, \Nette\DI\Container $container, $persistent = FALSE) { $config = $container->parameters['testbench']; $this->__testbench_databaseName = $config['dbprefix'] . getenv(\Tester\Environment::THREAD); $this->__testbench_database_drop($connection, $container); $this->__testbench_database_create($connection, $container); foreach ($config['sqls'] as $file) { \Kdyby\Doctrine\Dbal\BatchImport\Helpers::loadFromFile($connection, $file); } if ($config['migrations'] === TRUE) { if (class_exists(\Zenify\DoctrineMigrations\Configuration\Configuration::class)) { /** @var \Zenify\DoctrineMigrations\Configuration\Configuration $migrationsConfig */ $migrationsConfig = $container->getByType(\Zenify\DoctrineMigrations\Configuration\Configuration::class); $migrationsConfig->__construct($container, $connection); $migrationsConfig->registerMigrationsFromDirectory($migrationsConfig->getMigrationsDirectory()); $migration = new \Doctrine\DBAL\Migrations\Migration($migrationsConfig); $migration->migrate($migrationsConfig->getLatestVersion()); } } if ($persistent === FALSE) { register_shutdown_function(function () use($connection, $container) { $this->__testbench_database_drop($connection, $container); }); } }
/** * PHOCOA's default error handling is to try to catch *all* fatal errors and run them through the framework's error handling system. * * The error handling system unifies excptions and errors into the same processing stream and additionally gives your application * an opportunity to handle the error as well. For instance your app may prefer to email out all errors, * or send them to an exception service like Hoptoad/Exceptional/Loggly */ private function registerErrorHandlers() { // convert these errors into exceptions set_error_handler(array($this, 'handleError'), $this->handleErrors); // catch non-catchable errors register_shutdown_function(array($this, 'checkShutdownForFatalErrors')); }
public function __construct($name = null, $cacheLimiter = null, $wrapperInstance = null) { $this->name = $name; /* | Override native session handler */ $this->sessionSaveHandler(); /* | Get user configuration */ $this->config = Config::get('config.session'); /* | Set Database and Table for storing | session into database */ $this->database($this->config['database_name']); $this->table($this->config['table']); $this->setWrapperInstance($wrapperInstance); /* |Check if session started if not we will start new session |if session started already we will try */ if (!session_id()) { $this->start(); } $this->storage =& $_SESSION; /* | Check csrf token already exists into session | else regenerate the token */ $this->checkToken(); // This line prevents unexpected effects when using objects as save handlers. register_shutdown_function('session_write_close'); }