Bitrix-D7 22.2
Загрузка...
Поиск...
Не найдено
application.php
См. документацию.
1<?php
8namespace Bitrix\Main;
9
20
24abstract class Application
25{
27 const JOB_PRIORITY_LOW = 50;
28
32 protected static $instance;
33
34 protected bool $initialized = false;
35
41 protected $context;
42
44 protected $router;
45
47 protected $currentRoute;
48
53 protected $connectionPool;
54
59 protected $managedCache;
60
65 protected $taggedCache;
66
68 protected $session;
70 protected $kernelSession;
75
76 /*
77 * @var \SplPriorityQueue
78 */
79 protected $backgroundJobs;
80
82 protected $license;
83
87 protected function __construct()
88 {
89 ServiceLocator::getInstance()->registerByGlobalSettings();
90 $this->backgroundJobs = new \SplPriorityQueue();
92 $this->initializeCache();
94 }
95
101 public static function getInstance()
102 {
103 if (!isset(static::$instance))
104 {
105 static::$instance = new static();
106 }
107 return static::$instance;
108 }
109
113 public static function hasInstance()
114 {
115 return isset(static::$instance);
116 }
117
122 public function initializeBasicKernel()
123 {
124 }
125
131 public function initializeExtendedKernel(array $params)
132 {
133 $this->initializeContext($params);
134
135 if (!$this->initialized)
136 {
137 $this->initializeSessions();
138 $this->initializeSessionLocalStorage();
139
140 $this->initialized = true;
141 }
142 }
143
144 private function initializeSessions()
145 {
146 $resolver = new SessionConfigurationResolver(Configuration::getInstance());
147 $resolver->resolve();
148
149 $this->session = $resolver->getSession();
150 $this->kernelSession = $resolver->getKernelSession();
151
152 $this->compositeSessionManager = new CompositeSessionManager(
153 $this->kernelSession,
154 $this->session
155 );
156 }
157
158 private function initializeSessionLocalStorage()
159 {
160 $cacheEngine = Data\Cache::createCacheEngine();
161 if ($cacheEngine instanceof Data\LocalStorage\Storage\CacheEngineInterface)
162 {
163 $localSessionStorage = new Data\LocalStorage\Storage\CacheStorage($cacheEngine);
164 }
165 else
166 {
167 $localSessionStorage = new Data\LocalStorage\Storage\NativeSessionStorage(
168 $this->getSession()
169 );
170 }
171
172 $this->sessionLocalStorageManager = new Data\LocalStorage\SessionLocalStorageManager($localSessionStorage);
173 $configLocalStorage = Config\Configuration::getValue("session_local_storage") ?: [];
174 if (isset($configLocalStorage['ttl']))
175 {
176 $this->sessionLocalStorageManager->setTtl($configLocalStorage['ttl']);
177 }
178 }
179
183 public function getRouter(): Router
184 {
185 return $this->router;
186 }
187
191 public function setRouter(Router $router): void
192 {
193 $this->router = $router;
194 }
195
199 public function getCurrentRoute(): Route
200 {
201 return $this->currentRoute;
202 }
203
207 public function setCurrentRoute(Route $currentRoute): void
208 {
209 $this->currentRoute = $currentRoute;
210 }
211
217 abstract protected function initializeContext(array $params);
218
223 abstract public function start();
224
231 public function run()
232 {
233 }
234
245 public function end($status = 0, Response $response = null)
246 {
247 if($response === null)
248 {
249 //use default response
250 $response = $this->context->getResponse();
251
252 //it's possible to have open buffers
253 $content = '';
254 $n = ob_get_level();
255 while(($c = ob_get_clean()) !== false && $n > 0)
256 {
257 $content .= $c;
258 $n--;
259 }
260
261 if($content <> '')
262 {
263 $response->appendContent($content);
264 }
265 }
266
267 $this->handleResponseBeforeSend($response);
268 //this is the last point of output - all output below will be ignored
269 $response->send();
270
271 $this->terminate($status);
272 }
273
274 protected function handleResponseBeforeSend(Response $response): void
275 {
277 if (!($kernelSession instanceof KernelSessionProxy) && $kernelSession->isStarted())
278 {
279 //save session data in cookies
280 $kernelSession->getSessionHandler()->setResponse($response);
281 $kernelSession->save();
282 }
283 }
284
292 public function terminate($status = 0)
293 {
294 //old kernel staff
295 \CMain::RunFinalActionsInternal();
296
297 //Release session
298 session_write_close();
299
300 $pool = $this->getConnectionPool();
301
302 $pool->useMasterOnly(true);
303
304 $this->runBackgroundJobs();
305
306 $pool->useMasterOnly(false);
307
308 Data\ManagedCache::finalize();
309
310 $pool->disconnect();
311
312 exit($status);
313 }
314
340 protected function initializeExceptionHandler()
341 {
342 $exceptionHandler = new Diag\ExceptionHandler();
343
344 $exceptionHandling = Config\Configuration::getValue("exception_handling");
345 if ($exceptionHandling == null)
346 $exceptionHandling = array();
347
348 if (!isset($exceptionHandling["debug"]) || !is_bool($exceptionHandling["debug"]))
349 $exceptionHandling["debug"] = false;
350 $exceptionHandler->setDebugMode($exceptionHandling["debug"]);
351
352 if (isset($exceptionHandling["handled_errors_types"]) && is_int($exceptionHandling["handled_errors_types"]))
353 $exceptionHandler->setHandledErrorsTypes($exceptionHandling["handled_errors_types"]);
354
355 if (isset($exceptionHandling["exception_errors_types"]) && is_int($exceptionHandling["exception_errors_types"]))
356 $exceptionHandler->setExceptionErrorsTypes($exceptionHandling["exception_errors_types"]);
357
358 if (isset($exceptionHandling["ignore_silence"]) && is_bool($exceptionHandling["ignore_silence"]))
359 $exceptionHandler->setIgnoreSilence($exceptionHandling["ignore_silence"]);
360
361 if (isset($exceptionHandling["assertion_throws_exception"]) && is_bool($exceptionHandling["assertion_throws_exception"]))
362 $exceptionHandler->setAssertionThrowsException($exceptionHandling["assertion_throws_exception"]);
363
364 if (isset($exceptionHandling["assertion_error_type"]) && is_int($exceptionHandling["assertion_error_type"]))
365 $exceptionHandler->setAssertionErrorType($exceptionHandling["assertion_error_type"]);
366
367 $exceptionHandler->initialize(
368 array($this, "createExceptionHandlerOutput"),
369 array($this, "createExceptionHandlerLog")
370 );
371
372 ServiceLocator::getInstance()->addInstance('exceptionHandler', $exceptionHandler);
373 }
374
376 {
377 $exceptionHandling = Config\Configuration::getValue("exception_handling");
378
379 if (!is_array($exceptionHandling) || !isset($exceptionHandling["log"]) || !is_array($exceptionHandling["log"]))
380 {
381 return null;
382 }
383
384 $options = $exceptionHandling["log"];
385
386 $log = null;
387
388 if (isset($options["class_name"]) && !empty($options["class_name"]))
389 {
390 if (isset($options["extension"]) && !empty($options["extension"]) && !extension_loaded($options["extension"]))
391 {
392 return null;
393 }
394
395 if (isset($options["required_file"]) && !empty($options["required_file"]) && ($requiredFile = Loader::getLocal($options["required_file"])) !== false)
396 {
397 require_once($requiredFile);
398 }
399
400 $className = $options["class_name"];
401 if (!class_exists($className))
402 {
403 return null;
404 }
405
406 $log = new $className();
407 }
408 elseif (isset($options["settings"]) && is_array($options["settings"]))
409 {
410 $log = new Diag\FileExceptionHandlerLog();
411 }
412 else
413 {
414 return null;
415 }
416
417 $log->initialize(
418 isset($options["settings"]) && is_array($options["settings"]) ? $options["settings"] : array()
419 );
420
421 return $log;
422 }
423
425 {
426 return new Diag\ExceptionHandlerOutput();
427 }
428
432 protected function createDatabaseConnection()
433 {
434 $this->connectionPool = new Data\ConnectionPool();
435 }
436
437 protected function initializeCache()
438 {
439 //TODO: Should be transfered to where GET parameter is defined in future
440 //magic parameters: show cache usage statistics
441 $show_cache_stat = "";
442 if (isset($_GET["show_cache_stat"]))
443 {
444 $show_cache_stat = (strtoupper($_GET["show_cache_stat"]) == "Y" ? "Y" : "");
445 @setcookie("show_cache_stat", $show_cache_stat, false, "/");
446 }
447 elseif (isset($_COOKIE["show_cache_stat"]))
448 {
449 $show_cache_stat = $_COOKIE["show_cache_stat"];
450 }
451 Data\Cache::setShowCacheStat($show_cache_stat === "Y");
452
453 if (isset($_GET["clear_cache_session"]))
454 Data\Cache::setClearCacheSession($_GET["clear_cache_session"] === 'Y');
455 if (isset($_GET["clear_cache"]))
456 Data\Cache::setClearCache($_GET["clear_cache"] === 'Y');
457 }
458
462 public function getExceptionHandler()
463 {
464 return ServiceLocator::getInstance()->get('exceptionHandler');
465 }
466
472 public function getConnectionPool()
473 {
475 }
476
482 public function getContext()
483 {
484 return $this->context;
485 }
486
492 public function setContext(Context $context)
493 {
494 $this->context = $context;
495 }
496
497 public function getLicense(): License
498 {
499 if (!$this->license)
500 {
501 $this->license = new License();
502 }
503
504 return $this->license;
505 }
506
515 public static function getConnection($name = "")
516 {
517 $pool = Application::getInstance()->getConnectionPool();
518 return $pool->getConnection($name);
519 }
520
526 public function getCache()
527 {
528 return Data\Cache::createInstance();
529 }
530
536 public function getManagedCache()
537 {
538 if ($this->managedCache == null)
539 {
540 $this->managedCache = new Data\ManagedCache();
541 }
542
543 return $this->managedCache;
544 }
545
551 public function getTaggedCache()
552 {
553 if ($this->taggedCache == null)
554 {
555 $this->taggedCache = new Data\TaggedCache();
556 }
557
558 return $this->taggedCache;
559 }
560
561 final public function getSessionLocalStorageManager(): Data\LocalStorage\SessionLocalStorageManager
562 {
564 }
565
566 final public function getLocalSession($name): Data\LocalStorage\SessionLocalStorage
567 {
568 return $this->sessionLocalStorageManager->get($name);
569 }
570
571 final public function getKernelSession(): SessionInterface
572 {
574 }
575
576 final public function getSession(): SessionInterface
577 {
578 return $this->session;
579 }
580
582 {
584 }
585
591 public static function getUserTypeManager()
592 {
593 global $USER_FIELD_MANAGER;
594 return $USER_FIELD_MANAGER;
595 }
596
602 public static function isUtfMode()
603 {
604 static $isUtfMode = null;
605 if ($isUtfMode === null)
606 {
607 $isUtfMode = Config\Configuration::getValue("utf_mode");
608 if ($isUtfMode === null)
609 $isUtfMode = false;
610 }
611 return $isUtfMode;
612 }
613
619 public static function getDocumentRoot()
620 {
621 static $documentRoot = null;
622 if ($documentRoot != null)
623 return $documentRoot;
624
625 $context = Application::getInstance()->getContext();
626 if ($context != null)
627 {
628 $server = $context->getServer();
629 if ($server != null)
630 return $documentRoot = $server->getDocumentRoot();
631 }
632
634 }
635
641 public static function getPersonalRoot()
642 {
643 static $personalRoot = null;
644 if ($personalRoot != null)
645 return $personalRoot;
646
647 $context = Application::getInstance()->getContext();
648 if ($context != null)
649 {
650 $server = $context->getServer();
651 if ($server != null)
652 return $personalRoot = $server->getPersonalRoot();
653 }
654
655 return $_SERVER["BX_PERSONAL_ROOT"] ?? '/bitrix';
656 }
657
661 public static function resetAccelerator()
662 {
663 if (defined("BX_NO_ACCELERATOR_RESET"))
664 return;
665
666 $fl = Config\Configuration::getValue("no_accelerator_reset");
667 if ($fl)
668 return;
669
670 if (function_exists("accelerator_reset"))
671 accelerator_reset();
672 elseif (function_exists("wincache_refresh_if_changed"))
673 wincache_refresh_if_changed();
674 }
675
683 public function addBackgroundJob(callable $job, array $args = [], $priority = self::JOB_PRIORITY_NORMAL)
684 {
685 $this->backgroundJobs->insert([$job, $args], $priority);
686
687 return $this;
688 }
689
690 protected function runBackgroundJobs()
691 {
692 $lastException = null;
693 $exceptionHandler = $this->getExceptionHandler();
694
695 //jobs can be added from jobs
696 while($this->backgroundJobs->valid())
697 {
698 //clear the queue
699 $jobs = [];
700 foreach ($this->backgroundJobs as $job)
701 {
702 $jobs[] = $job;
703 }
704
705 //do job
706 foreach ($jobs as $job)
707 {
708 try
709 {
710 call_user_func_array($job[0], $job[1]);
711 }
712 catch (\Throwable $exception)
713 {
714 $lastException = $exception;
715 $exceptionHandler->writeToLog($exception);
716 }
717 }
718 }
719
720 if ($lastException !== null)
721 {
722 throw $lastException;
723 }
724 }
725
730 public function isInitialized()
731 {
732 return $this->initialized;
733 }
734}
handleResponseBeforeSend(Response $response)
setContext(Context $context)
setCurrentRoute(Route $currentRoute)
addBackgroundJob(callable $job, array $args=[], $priority=self::JOB_PRIORITY_NORMAL)
initializeContext(array $params)
setRouter(Router $router)
static getConnection($name="")
end($status=0, Response $response=null)
initializeExtendedKernel(array $params)
static getDocumentRoot()
Definition: loader.php:248
static getLocal($path, $root=null)
Definition: loader.php:523