/** * Enables the debug tools. * * This method registers an error handler and an exception handler. * * If the Symfony ClassLoader component is available, a special * class loader is also registered. * * @param int $errorReportingLevel The level of error reporting you want * @param bool $displayErrors Whether to display errors (for development) or just log them (for production) */ public static function enable($errorReportingLevel = null, $displayErrors = true) { if (static::$enabled) { return; } static::$enabled = true; if ($errorReportingLevel !== null) { error_reporting($errorReportingLevel); } else { error_reporting(-1); } if ('cli' !== php_sapi_name()) { ini_set('display_errors', 0); ExceptionHandler::register(); } else { if ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) { // CLI - display errors only if they're not already logged to STDERR ini_set('display_errors', 1); } } if ($displayErrors) { error_handler::register(new error_handler(new BufferingLogger())); } else { error_handler::register()->throwAt(0, true); } DebugClassLoader::enable(); }
public function bootstrap() { $app = $this; $app['dir.base'] = __DIR__ . "/../../../../"; $app->register(new ConfigServiceProvider()); $app['debug'] = $app['config']['debug']; ErrorHandler::register(); ExceptionHandler::register($app['debug']); $app->register(new HttpFragmentServiceProvider()); $app->register(new ServiceControllerServiceProvider()); $app->register(new ORMServiceProvider()); $app->register(new SessionServiceProvider()); $app->register(new SecurityServiceProvider()); $app['security.encoder.digest'] = function ($app) { // uses the password-compat encryption return new BCryptPasswordEncoder(10); }; $app->register(new ManagerRegistryServiceProvider()); $app['security.firewalls'] = array('default' => array('pattern' => '/', 'form' => array('login_path' => '/login', 'check_path' => '/login_check'), 'logout' => array('logout_path' => '/logout', 'invalidate_session' => true), 'users' => function () use($app) { return new EntityUserProvider($app['manager_registry'], User::class, 'username'); }, 'anonymous' => true)); $app['security.access_rules'] = [['^/admin', 'ROLE_ADMIN']]; $app->register(new TranslationServiceProvider(), array('locale_fallbacks' => array('en'), 'locale' => 'en')); $app->register(new ValidatorServiceProvider()); $app->register(new FormServiceProvider()); $app->register(new TwigServiceProvider(), ['twig.path' => __DIR__ . '/../resources/views', 'twig.form.templates' => ['bootstrap_3_layout.html.twig'], 'twig.strict_variables' => false]); $app->extend('twig', function (\Twig_Environment $twig) { $twig->addTest(new \Twig_SimpleTest('callable', function ($variable) { return is_callable($variable); })); $twig->addFunction(new \Twig_SimpleFunction('is_callable', function ($variable) { return is_callable($variable); })); $twig->addFunction(new \Twig_SimpleFunction('call_user_func', function ($callable, $params = null) { return call_user_func($callable, $params); })); $twig->getExtension('core')->setDateFormat('Y/m/d', '%d days'); return $twig; }); $app->extend('form.types', function ($types) use($app) { $types[] = new EntityType($app['manager_registry']); $types[] = new TemplateChoiceType($app['theme']); $types[] = new PageType($app['theme']); return $types; }); $app->register(new SerializerServiceProvider()); $app->register(new WebProfilerServiceProvider(), ['profiler.cache_dir' => './../storage/framework/cache/profiler', 'web_profiler.debug_toolbar.enable' => $app['debug'], 'profiler.mount_prefix' => '/admin/_profiler']); $app['finder'] = function () { return new Finder(); }; $app['filesystem'] = function () { return new Filesystem(); }; $app->register(new ConverterServiceProvider()); $app->register(new ThemeServiceProvider()); $app['twig.loader.filesystem']->addPath($app['dir.theme'], 'theme'); $app->register(new CMSServiceProvider()); $app->setRoutes(); }
public function register(Application $app) { $debug = isset($app['config']) ? $app['config']['app.debug'] : true; $handler = ExceptionHandler::register($debug); ErrorHandler::register(E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR); if ($cli = $app->runningInConsole() or $debug) { ini_set('display_errors', 1); } $app['exception'] = $handler; }
public function register(Application $app) { ErrorHandler::register(); ExceptionHandler::register($app['debug']); $app->error(function (\Exception $exception, $code) use($app) { if (!$app['debug'] || $code === 404) { // 404.html, or 40x.html, or 4xx.html, or error.html $templates = array('errors/' . $code . '.html.twig', 'errors/' . substr($code, 0, 2) . 'x.html.twig', 'errors/' . substr($code, 0, 1) . 'xx.html.twig', 'errors/' . 'default.html.twig'); return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code); } }); }
public function __construct() { parent::__construct(); // Convert errors to exceptions ErrorHandler::register(); ExceptionHandler::register(); $this['cache.directory'] = __DIR__ . '/../../../app/cache'; $this['vendor.directory'] = __DIR__ . '/../../../vendor'; $this->registerControllers(); $this->registerServiceProviders(); $this->registerInternalServices(); }
/** * Enables the debug tools. * * This method registers an error handler and an exception handler. * * If the Symfony ClassLoader component is available, a special * class loader is also registered. * * @param integer $errorReportingLevel The level of error reporting you want * @param Boolean $displayErrors Whether to display errors (for development) or just log them (for production) */ public static function enable($errorReportingLevel = null, $displayErrors = true) { if (static::$enabled) { return; } static::$enabled = true; error_reporting(-1); ErrorHandler::register($errorReportingLevel, $displayErrors); if ('cli' !== php_sapi_name()) { ExceptionHandler::register(); // CLI - display errors only if they're not already logged to STDERR } elseif ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) { ini_set('display_errors', 1); } DebugClassLoader::enable(); }
/** * Enables the debug tools. * * This method registers an error handler and an exception handler. * * If the Symfony ClassLoader component is available, a special * class loader is also registered. * * @param integer $errorReportingLevel The level of error reporting you want */ public static function enable($errorReportingLevel = null) { if (static::$enabled) { return; } static::$enabled = true; error_reporting(-1); ErrorHandler::register($errorReportingLevel); if ('cli' !== php_sapi_name()) { ExceptionHandler::register(); } elseif (!ini_get('log_errors') || ini_get('error_log')) { ini_set('display_errors', 1); } if (class_exists('Symfony\\Component\\ClassLoader\\DebugClassLoader')) { DebugClassLoader::enable(); } }
public function onKernelException(GetResponseForExceptionEvent $e) { $ex = $e->getException(); $response = new Response(); if ($ex instanceof NotFoundHttpException) { $response->setContent($this->view->render('error/404')); $e->setResponse($response); return; } if ($this->debugMode) { \Symfony\Component\Debug\ExceptionHandler::register(); throw $ex; } $response->setContent($this->view->render('error/exception')); $e->setResponse($response); $this->logger->handleException($ex); }
/** * Sets default exception handler. * * If shop is in productive mode stick to default OXID exception handler * Else register Symfony Debug component's Exception and Error handlers * * Non-productive eShop mode is intended for eShop installation, configuration, template customization and module debugging phase. * As soon as productive mode is turned ON, the cache handling and the error reporting behavior is optimized for the live shop. */ protected function _setDefaultExceptionHandler() { /** * @todo: consider also getEnvironment() function to detect environment */ if (oxRegistry::getConfig()->isProductiveMode()) { parent::_setDefaultExceptionHandler(); return; } /** * Debug::enable() also registers a DebugClassLoader which throw an error because oxid does not care about case when referring to objects * symfony is key sensitive: oxarticlelist != oxArticleList */ //Debug\Debug::enable(); ini_set('display_errors', 0); Debug\ExceptionHandler::register(); Debug\ErrorHandler::register()->throwAt(0, true); }
/** * Enables the debug tools. * * This method registers an error handler and an exception handler. * * If the Symfony ClassLoader component is available, a special * class loader is also registered. * * @param int $errorReportingLevel The level of error reporting you want * @param bool $displayErrors Whether to display errors (for development) or just log them (for production) */ public static function enable($errorReportingLevel = null, $displayErrors = true) { if (static::$enabled) { return; } static::$enabled = true; error_reporting(-1); ErrorHandler::register($errorReportingLevel, $displayErrors); if ('cli' !== PHP_SAPI) { ExceptionHandler::register(); // CLI - display errors only if they're not already logged to STDERR } elseif ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) { ini_set('display_errors', 1); } if (class_exists('Symfony\\Component\\ClassLoader\\DebugClassLoader')) { DebugClassLoader::enable(); } }
/** * Init config * * @param Application $app */ private function _iniConfig(Application $app) { // Setting the sign of the console $app['is_console'] = TRUE; // Load configurations $app->register(new Providers\YamlConfigServiceProvider(array('%base_path%' => BASEPATH, '%log_path%' => BASEPATH . '/data/logs', '%cache_path%' => BASEPATH . '/data/cache')), array('config.dir' => BASEPATH . '/app/Resources/Config', 'config.files' => array('console.yml'))); //Set debug option $app['debug'] = $app['config']['parameters']['debug']; //Set basepath option $app['basepath'] = $this->app['config']['base_path']; //Set Timezone if (isset($app['config']['parameters']['timezone'])) { date_default_timezone_set($app['config']['parameters']['timezone']); } // Registering the ErrorHandler // It converts all errors to exceptions, and exceptions are then caught by Silex ErrorHandler::register(); ExceptionHandler::register($app['debug']); }
/** * Set the handlers. * * @param bool $debug */ public static function register($debug = true) { $errorLevels = error_reporting(); if ($debug) { $errorLevels |= E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED; Debug\DebugClassLoader::enable(); } if (PHP_SAPI !== 'cli') { Debug\ErrorHandler::register()->throwAt($errorLevels, true); Debug\ExceptionHandler::register($debug); } else { $consoleHandler = function (\Exception $e) { $app = new Application('Bolt CLI', Version::VERSION); $output = new ConsoleOutput(OutputInterface::VERBOSITY_DEBUG); $app->renderException($e, $output); ob_clean(); }; Debug\ExceptionHandler::register($debug)->setHandler($consoleHandler); } }
public function connect(Application $app) { ExceptionHandler::register(false); $controllers = $app['controllers_factory']; $self = $this; // first screen $controllers->get('/eula/{language}', function (Request $request, $language) use($app, $self) { return $app['twig']->render("static/eula_{$language}.twig", array()); }); $controllers->get('/privacypolicy/{language}', function (Request $request, $language) use($app, $self) { return $app['twig']->render("static/privacy_{$language}.twig", array()); }); $controllers->get('/information/{token}', function (Request $request, $token) use($app, $self) { $user = $app['spikadb']->findUserByToken($token); if (empty($user['token']) || $token !== $user['token']) { return $app['twig']->render("static/tokenExpired.twig", array('ROOT_URL' => ROOT_URL)); } $app['session']->set('user', $user); return $app['twig']->render("static/information.twig", array('ROOT_URL' => ROOT_URL, 'user' => $user)); }); return $controllers; }
protected function initEnvironment() { error_reporting(-1); if ($this->container['environment'] === 'debug') { ExceptionHandler::register(); } else { if ($this->container['environment'] === 'production') { error_reporting(E_ALL ^ (E_STRICT | E_NOTICE | E_DEPRECATED)); ini_set('display_errors', 0); } $listener = new ExceptionListener($this->container['error_controller']); $this->container['dispatcher']->addSubscriber($listener); } $handler = ErrorHandler::register(null, true); $handler->setDefaultLogger($this->container['logger.logger']); }
public function initialise() { // File System $this->registry->set('filesystem', new Filesystem()); // Config $this->registry->set('config', new Config()); // Database $this->registry->set('db', new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE)); // Store if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == '1')) { $store_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $this->db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'"); } else { $store_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $this->db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'"); } if ($store_query->num_rows) { $this->config->set('config_store_id', $store_query->row['store_id']); } else { $this->config->set('config_store_id', 0); } // Settings $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "setting` WHERE store_id = '0' OR store_id = '" . (int) $this->config->get('config_store_id') . "' ORDER BY store_id ASC"); foreach ($query->rows as $result) { if (!$result['serialized']) { $this->config->set($result['key'], $result['value']); } else { $this->config->set($result['key'], unserialize($result['value'])); } } if (!$store_query->num_rows) { $this->config->set('config_url', HTTP_SERVER); $this->config->set('config_ssl', HTTPS_SERVER); } // Loader $this->registry->set('load', new Loader($this->registry)); // Trigger $this->registry->set('trigger', new Trigger($this->registry)); // Url $this->registry->set('url', new Url($this->config->get('config_url'), $this->config->get('config_ssl'), $this->registry)); // Uri $this->registry->set('uri', new Uri()); // Log $this->registry->set('log', new Log($this->config->get('config_error_filename'))); // Error Handler if ($this->config->get('config_error_display', 0) == 2) { ErrorHandler::register(); ExceptionHandler::register(); } else { set_error_handler(array($this, 'errorHandler')); } // Security $this->registry->set('security', new Security($this->registry)); // Request $this->registry->set('request', new Request($this->registry)); // Response $response = new Response(); $response->addHeader('Content-Type: text/html; charset=utf-8'); $response->setCompression($this->config->get('config_compression')); $this->registry->set('response', $response); // Cache $cache = new Cache($this->config->get('config_cache_storage', 'file'), $this->config->get('config_cache_lifetime', 86400)); $this->registry->set('cache', $cache); // Session $this->registry->set('session', new Session()); // Utility $utility = new Utility($this->registry); $this->registry->set('utility', $utility); // Language Detection $language = $utility->getLanguage(); if (!isset($this->session->data['language']) || $this->session->data['language'] != $language['code']) { $this->session->data['language'] = $language['code']; } if (!isset($this->request->cookie['language']) || $this->request->cookie['language'] != $language['code']) { setcookie('language', $language['code'], time() + 60 * 60 * 24 * 30, '/', $this->request->server['HTTP_HOST']); } $this->config->set('config_language', $language['code']); $this->config->set('config_language_dir', $language['directory']); $this->config->set('config_language_id', $language['language_id']); // Language $this->registry->set('language', new Language($language['directory'], $this->registry)); // Page Cache $pagecache = new Pagecache($this->registry); $pagecache->getPage(); $this->registry->set('pagecache', $pagecache); // Document $this->registry->set('document', new Document()); $this->trigger->fire('post.app.initialise'); }
require_once __DIR__.'/api/vendor/autoload.php'; require_once __DIR__."/api/src/functions/link_to.php"; require_once __DIR__."/api/src/functions/LinkTo.php"; require_once __DIR__."/api/src/functions/Format.php"; //xdebug_disable(); error_reporting(0); PHPTemplate::setTemplateDir([ __DIR__."/api/src/templates" ]); $app = new Silex\Application(); $app['debug'] = true; \Symfony\Component\Debug\ErrorHandler::register(); \Symfony\Component\Debug\ExceptionHandler::register(); /** ** Load the front end that contains the JS app via app/index.php */ $app->get('/', function () use ($app) { $text = file_get_contents(__DIR__ . "/app/index.php"); return $text; }); // // Document NON_REST interface // $app->match('/api/v1.0/document/{method}/{name}', function ($name, $method) use ($app) { $controller = new \Controller\Json();
/** * Init config * * @param Application $app */ private function _iniConfig(Application $app) { // Set type configuration $app['yml_config'] = FALSE; // Setting the sign of the console $app['is_console'] = FALSE; // Load configurations if ($app['yml_config']) { $app->register(new Providers\YamlConfigServiceProvider(array('%base_path%' => BASEPATH, '%log_path%' => BASEPATH . '/data/logs', '%cache_path%' => BASEPATH . '/data/cache')), array('config.dir' => BASEPATH . '/app/Resources/Config', 'config.files' => array('application.yml', 'security.yml'))); } else { $app['config'] = $app->share(function () use($app) { $params = array(); //--------------------- $params['base_path'] = BASEPATH; $params['log_path'] = BASEPATH . "/data/logs"; $params['cache_path'] = BASEPATH . "/data/cache"; $fileConfig = is_file(BASEPATH . '/env.yml') ? BASEPATH . '/env.yml' : BASEPATH . '/app/Resources/Config/parameters.yml'; $data = Yaml::parse(file_get_contents($fileConfig)); foreach ($data['parameters'] as $key => $value) { $params['parameters'][$key] = $this->_formatIniValue($value); } foreach ($data['controllers'] as $key => $value) { $params['controllers'][$key] = $this->_formatIniValue($value); } return $params; }); } //Set debug option $app['debug'] = $app['config']['parameters']['debug']; //Set basepath option $app['basepath'] = $this->app['config']['base_path']; //Set Timezone if (isset($app['config']['parameters']['timezone'])) { date_default_timezone_set($app['config']['parameters']['timezone']); } // Registering the ErrorHandler // It converts all errors to exceptions, and exceptions are then caught by Silex ErrorHandler::register(); ExceptionHandler::register($app['debug']); }
<?php date_default_timezone_set('UTC'); require_once __DIR__ . '/../vendor2/autoload.php'; use Doctrine\DBAL\DriverManager; use Topxia\Service\Common\ServiceKernel; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\ParameterBag; // use Symfony\Component\Debug\Debug; // Debug::enable(); ErrorHandler::register(0); ExceptionHandler::register(false); $config = (include __DIR__ . '/config.php'); $config['host'] = 'http://' . $_SERVER['HTTP_HOST']; $connection = DriverManager::getConnection(array('wrapperClass' => 'Topxia\\Service\\Common\\Connection', 'dbname' => $config['database_name'], 'user' => $config['database_user'], 'password' => $config['database_password'], 'host' => $config['database_host'], 'driver' => $config['database_driver'], 'charset' => 'utf8')); $serviceKernel = ServiceKernel::create($config['environment'], true); $serviceKernel->setParameterBag(new ParameterBag($config)); $serviceKernel->setConnection($connection); // $serviceKernel->getConnection()->exec('SET NAMES UTF8'); include __DIR__ . '/src/functions.php'; $app = new Silex\Application(); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->view(function (array $result, Request $request) use($app) { return new JsonResponse($result); }); include __DIR__ . '/config/container.php'; $app->before(function (Request $request) use($app) { $whiteLists = (include __DIR__ . '/whiteList.php');
/** * Prepare the environment, registering the Error and Exception handlers, and allowing HTTP method parameter overriding. */ protected function bootstrapEnvironment() { $this["debug"] = !!$this["app.config"]["environment.debug"]; Errorhandler::register(); ExceptionHandler::register($this["debug"]); Request::enableHttpMethodParameterOverride(); }
<?php use Silex\Application; use Symfony\Component\Debug\Debug; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; defined('APP_PATH') || define('APP_PATH', realpath(dirname(__FILE__) . '/../')); // Define application environment defined('APP_ENV') || define('APP_ENV', getenv('APP_ENV') ? getenv('APP_ENV') : 'prod'); // Define application environment defined('APP_DEBUG') || define('APP_DEBUG', getenv('APP_DEBUG') ? (bool) getenv('APP_DEBUG') : false); if (APP_DEBUG === false) { ini_set('display_errors', 0); } require_once APP_PATH . '/vendor/autoload.php'; ErrorHandler::register(); ExceptionHandler::register(APP_DEBUG); if (APP_DEBUG === true) { Debug::enable(); } /** @var Application $app */ $app = (require APP_PATH . '/app/kernel.php'); $app->run();
<?php use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; require_once __DIR__ . '/../vendor/autoload.php'; $app = (require __DIR__ . '/../src/app.php'); ErrorHandler::register(); ExceptionHandler::register(); require __DIR__ . '/../config/dev.php'; require __DIR__ . '/../src/Http/Routes.php'; $app['capsule']; $app->run();
<?php use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\Debug\ErrorHandler; ErrorHandler::register(); ExceptionHandler::register($app['debug']); $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { throw $e; } });
/** * Register web debugger and exception handler. */ protected function registerWebDebugger() { ErrorHandler::register(); ExceptionHandler::register(env('APP_DEBUG', false)); }
protected function registerErrorHandlers() { $app = $this; /** * Turn on some debugging features if in debug mode */ if ($app['debug']) { error_reporting(-1); ErrorHandler::register(); // CLI - display errors only if they're not already logged to STDERR if (!$app->isCli()) { ExceptionHandler::register(); } elseif (!ini_get('log_errors') || ini_get('error_log')) { ini_set('display_errors', 1); } } $app->error(function (\Exception $error) use($app) { return $app['twig']->render('view/error.twig', ['error' => $error]); }); }
private function registerErrorHandlers() { ErrorHandler::register($this['debug']); ExceptionHandler::register($this['debug']); }
public function connect(Application $app) { ExceptionHandler::register(false); $controllers = $app['controllers_factory']; $self = $this; // first screen $controllers->get('/installer', function (Request $request) use($app, $self) { $app['monolog']->addDebug("top"); $rootUrl = str_replace("/installer", "", $self->curPageURL()); return $app['twig']->render('installer/installerTop.twig', array('ROOT_URL' => $rootUrl)); }); // connect to DB $controllers->post('/installer/step1', function (Request $request) use($app, $self) { $app['monolog']->addDebug("step1"); $rootUrl = str_replace("/installer/step1", "", $self->curPageURL()); $host = $request->get('host'); $database = $request->get('database'); $userName = $request->get('username'); $password = $request->get('password'); $config = new \Doctrine\DBAL\Configuration(); $connectionParams = array('dbname' => $database, 'user' => $userName, 'password' => $password, 'host' => $host, 'driver' => 'pdo_mysql'); $app['session']->set('databaseConfiguration', $connectionParams); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); try { $connectionResult = $conn->connect(); } catch (\PDOException $e) { $connectionResult = false; $app['monolog']->addDebug("Failed to connect DB"); } if ($connectionResult) { return $app['twig']->render('installer/installerStep1.twig', array('ROOT_URL' => $rootUrl, 'ConnectionSucceed' => $connectionResult)); } else { return $app['twig']->render('installer/installerTop.twig', array('ROOT_URL' => $rootUrl, 'ConnectionSucceed' => $connectionResult)); } }); // create database schema $controllers->post('/installer/step2', function (Request $request) use($app, $self) { $app['monolog']->addDebug("step2"); $rootUrl = str_replace("/installer/step2", "", $self->curPageURL()); $config = new \Doctrine\DBAL\Configuration(); $connectionParams = $app['session']->get('databaseConfiguration'); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); try { $connectionResult = $conn->connect(); } catch (\PDOException $e) { $app->redirect('/installer'); } // read sql file $pathToSchemaFile = "../install/databaseschema.sql"; if (!file_exists("../install/databaseschema.sql")) { return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } $schemacontent = file_get_contents($pathToSchemaFile); $queries = explode(";", $schemacontent); $conn->beginTransaction(); try { foreach ($queries as $query) { $query = trim($query); if (!empty($query)) { $conn->executeQuery($query); } } $conn->commit(); } catch (\Exception $e) { $app['monolog']->addDebug($e->getMessage()); $conn->rollback(); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } return $app['twig']->render('installer/installerStep2.twig', array('ROOT_URL' => $rootUrl, 'ConnectionSucceed' => $connectionResult)); }); // generate initial data $controllers->post('/installer/step3', function (Request $request) use($app, $self) { $app['monolog']->addDebug("step3"); $rootUrl = str_replace("/installer/step3", "", $self->curPageURL()); $localRootUrl = str_replace("/installer/step3", "", $self->curPageURLLocal()); $config = new \Doctrine\DBAL\Configuration(); $connectionParams = $app['session']->get('databaseConfiguration'); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); try { $connectionResult = $conn->connect(); } catch (\PDOException $e) { $app['monolog']->addDebug("failed to connect DB" . var_dump($connectionParams)); $app['monolog']->addDebug($e->getMessage()); $app->redirect('/installer'); } $fileDir = __DIR__ . '/../../../../../' . FileController::$fileDirName; if (!is_writable($fileDir)) { $app['monolog']->addDebug("{$fileDir} is not writable."); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } $conn->beginTransaction(); // generate group categories $files = array(); $filesPath = __DIR__ . '/../../../../../install/resouces/categoryimages'; if ($handle = opendir($filesPath)) { while ($entry = readdir($handle)) { if (is_file($filesPath . "/" . $entry)) { if (preg_match("/png/", $entry)) { $files[] = $filesPath . "/" . $entry; } } } closedir($handle); } foreach ($files as $path) { // copy to file dir $pathinfo = pathinfo($path); $categoryName = $pathinfo['filename']; $imgbinary = @file_get_contents($path); $fileName = \Spika\Utils::randString(20, 20) . time(); $newFilePath = $fileDir . "/" . $fileName; copy($path, $newFilePath); // create data $data = array('title' => $categoryName, 'avatar_file_id' => $fileName, 'created' => time()); try { $conn->insert('group_category', $data); } catch (\Exception $e) { $app['monolog']->addDebug($e->getMessage()); $conn->rollback(); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } } // generate emoticons $files = array(); $filesPath = __DIR__ . '/../../../../../install/resouces/emoticons'; if ($handle = opendir($filesPath)) { while ($entry = readdir($handle)) { if (is_file($filesPath . "/" . $entry)) { if (preg_match("/png/", $entry)) { $files[] = $filesPath . "/" . $entry; } } } closedir($handle); } foreach ($files as $path) { // copy to file dir $pathinfo = pathinfo($path); $emoticonname = $pathinfo['filename']; $imgbinary = @file_get_contents($path); $fileName = \Spika\Utils::randString(20, 20) . time(); $newFilePath = $fileDir . "/" . $fileName; copy($path, $newFilePath); // create data $data = array('identifier' => $emoticonname, 'file_id' => $fileName, 'created' => time()); try { $conn->insert('emoticon', $data); } catch (\Exception $e) { $app['monolog']->addDebug($e->getMessage()); $conn->rollback(); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } } // create support user $password = '******'; $userData = array(); $userData['name'] = "Administrator"; $userData['email'] = "*****@*****.**"; $userData['password'] = md5($password); $userData['online_status'] = "online"; $userData['max_contact_count'] = 100; $userData['max_favorite_count'] = 100; $userData['birthday'] = 0; $userData['created'] = time(); $conn->insert('user', $userData); $conn->commit(); return $app['twig']->render('installer/installerStep3.twig', array('ROOT_URL' => $rootUrl, 'LOCAL_ROOT_URL' => $localRootUrl, 'ConnectionSucceed' => $connectionResult, 'DbParams' => $connectionParams, 'SupportUserId' => $conn->lastInsertId("_id"))); }); return $controllers; }
<?php define('CONSOLE', true); require 'bootstrap.php'; use Symfony\Component\Debug\Debug; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\Console\Output\ConsoleOutput; $errorHandler = ErrorHandler::register(); $excepHandler = ExceptionHandler::register(); $errorHandler->setExceptionHandler(function (Exception $e) { $output = new ConsoleOutput(); $output->writeln('<error>' . $e->getMessage() . '</error>'); $output->writeln('<comment>' . $e->getTraceAsString() . '</comment>'); }); $app = (require 'application.php'); $app->registerServices($app['config']['services.console']); $app->boot(); /** * Search for command and register it */ $appReflection = new ReflectionClass($app); $commandPath = dirname($appReflection->getFileName()) . '/Console/Command'; $app['console']->setDispatcher($app['dispatcher']); $app['console']->registerCommandDirectory($commandPath, 'SilexStarter\\Console\\Command'); $app['console']->registerCommandDirectory($app['path.app'] . 'commands'); /** * Dispatch console.init event to register command previously registered in module manager */ $app['dispatcher']->dispatch('console.init'); return $app['console'];
<?php error_reporting(E_ALL); ini_set('display_errors', 0); ignore_user_abort(true); date_default_timezone_set('UTC'); require __DIR__ . '/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\DBAL\Connection; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; ErrorHandler::register(); ExceptionHandler::register()->setHandler(function (\Exception $e) { print 'INTERNAL_ERROR'; }); $app = new \Silex\Application(); $app['debug'] = false; $app->register(new \Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => '127.0.0.1', 'dbname' => 'lottery', 'user' => 'root', 'password' => '', 'charset' => 'utf8mb4'))); $app->register(new \Silex\Provider\ValidatorServiceProvider()); $app->error(function (\Exception $e, $code) use($app) { if ($code === 404) { return new Response('NOT_FOUND', $code); } return new Response('INTERNAL_ERROR', $code); }); $app->get('/', function (Request $req) use($app) { $params = $req->query->all(); $constraint = new Assert\Collection(array('user' => new Assert\Regex(array('pattern' => '/^[A-Za-z0-9]{5}$/')), 'code' => new Assert\Regex(array('pattern' => '/^[A-Za-z0-9]{5}$/')))); $errors = $app['validator']->validateValue($params, $constraint);
} use Xstatic\ProxyManager; use SilexStarter\SilexStarter; use SilexStarter\Provider\ConfigServiceProvider; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\HttpFoundation\Request; Request::enableHttpMethodParameterOverride(); /* Instantiate the extended Silex Application */ $app = new SilexStarter(); /* Load the configuration service provider and load base app configuration */ $app->register(new ConfigServiceProvider(), ['config.path' => APP_PATH . 'config']); $app['config']->load('app'); if (!$isConsole) { ErrorHandler::register(); ExceptionHandler::register($app['environment'] == 'development' && $app['debug']); } /* Register the service provider listed in app/config/services.php */ $app->registerServices($app['config']['services.common']); if (!$isConsole) { $app->registerServices($app['config']['services.web']); } if (!$isConsole && $app['environment'] == 'development') { $app->registerServices($app['config']['services.web_dev']); } /* Load module provider if enabled */ if ($app['enable_module']) { $app['module']->registerModules($app['config']['modules']); } /* Register all controller as service if enabled */ if ($app['controller_as_service'] && !isset($app['optimized_app'])) {
<?php require_once __DIR__ . '/../vendor/autoload.php'; define('API_DEUG', true); //Инициализация и регистрация обрабочиков ошибок php use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; ErrorHandler::register(); ExceptionHandler::register(API_DEUG); //Инициализация фреймворка $app = new Silex\Application(); //Подключение областей видимости компонентов use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; //Инициализация соединения с БД $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'dbname' => 'rest', 'host' => 'localhost', 'user' => 'root', 'password' => ''))); //Включение режима отладки $app['debug'] = API_DEUG; //Роуты //Корень - редирект на /api/users $app->get('/', function () use($app) { return $app->redirect('index.html'); }); //Корень API - редирект на страницу документации $app->get('/api/', function () use($app) { return 'Phonebook API works!'; }); //Получить список пользователей $app->get('/api/users/', function () use($app) { $sql = 'SELECT * FROM phonebook';