Bitrix-D7 22.6
 
Загрузка...
Поиск...
Не найдено
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 (!empty($exceptionHandling['track_modules']) && is_array($exceptionHandling['track_modules']))
353 {
354 $exceptionHandler->setTrackModules($exceptionHandling['track_modules']);
355 }
356
357 if (isset($exceptionHandling["handled_errors_types"]) && is_int($exceptionHandling["handled_errors_types"]))
358 $exceptionHandler->setHandledErrorsTypes($exceptionHandling["handled_errors_types"]);
359
360 if (isset($exceptionHandling["exception_errors_types"]) && is_int($exceptionHandling["exception_errors_types"]))
361 $exceptionHandler->setExceptionErrorsTypes($exceptionHandling["exception_errors_types"]);
362
363 if (isset($exceptionHandling["ignore_silence"]) && is_bool($exceptionHandling["ignore_silence"]))
364 $exceptionHandler->setIgnoreSilence($exceptionHandling["ignore_silence"]);
365
366 if (isset($exceptionHandling["assertion_throws_exception"]) && is_bool($exceptionHandling["assertion_throws_exception"]))
367 $exceptionHandler->setAssertionThrowsException($exceptionHandling["assertion_throws_exception"]);
368
369 if (isset($exceptionHandling["assertion_error_type"]) && is_int($exceptionHandling["assertion_error_type"]))
370 $exceptionHandler->setAssertionErrorType($exceptionHandling["assertion_error_type"]);
371
372 $exceptionHandler->initialize(
373 array($this, "createExceptionHandlerOutput"),
374 array($this, "createExceptionHandlerLog")
375 );
376
377 ServiceLocator::getInstance()->addInstance('exceptionHandler', $exceptionHandler);
378 }
379
381 {
382 $exceptionHandling = Config\Configuration::getValue("exception_handling");
383
384 if (!is_array($exceptionHandling) || !isset($exceptionHandling["log"]) || !is_array($exceptionHandling["log"]))
385 {
386 return null;
387 }
388
389 $options = $exceptionHandling["log"];
390
391 $log = null;
392
393 if (isset($options["class_name"]) && !empty($options["class_name"]))
394 {
395 if (isset($options["extension"]) && !empty($options["extension"]) && !extension_loaded($options["extension"]))
396 {
397 return null;
398 }
399
400 if (isset($options["required_file"]) && !empty($options["required_file"]) && ($requiredFile = Loader::getLocal($options["required_file"])) !== false)
401 {
402 require_once($requiredFile);
403 }
404
405 $className = $options["class_name"];
406 if (!class_exists($className))
407 {
408 return null;
409 }
410
411 $log = new $className();
412 }
413 elseif (isset($options["settings"]) && is_array($options["settings"]))
414 {
415 $log = new Diag\FileExceptionHandlerLog();
416 }
417 else
418 {
419 return null;
420 }
421
422 $log->initialize(
423 isset($options["settings"]) && is_array($options["settings"]) ? $options["settings"] : array()
424 );
425
426 return $log;
427 }
428
430 {
431 return new Diag\ExceptionHandlerOutput();
432 }
433
437 protected function createDatabaseConnection()
438 {
439 $this->connectionPool = new Data\ConnectionPool();
440 }
441
442 protected function initializeCache()
443 {
444 //TODO: Should be transfered to where GET parameter is defined in future
445 //magic parameters: show cache usage statistics
446 $show_cache_stat = "";
447 if (isset($_GET["show_cache_stat"]))
448 {
449 $show_cache_stat = (strtoupper($_GET["show_cache_stat"]) == "Y" ? "Y" : "");
450 @setcookie("show_cache_stat", $show_cache_stat, false, "/");
451 }
452 elseif (isset($_COOKIE["show_cache_stat"]))
453 {
454 $show_cache_stat = $_COOKIE["show_cache_stat"];
455 }
456 Data\Cache::setShowCacheStat($show_cache_stat === "Y");
457
458 if (isset($_GET["clear_cache_session"]))
459 Data\Cache::setClearCacheSession($_GET["clear_cache_session"] === 'Y');
460 if (isset($_GET["clear_cache"]))
461 Data\Cache::setClearCache($_GET["clear_cache"] === 'Y');
462 }
463
467 public function getExceptionHandler()
468 {
469 return ServiceLocator::getInstance()->get('exceptionHandler');
470 }
471
477 public function getConnectionPool()
478 {
480 }
481
487 public function getContext()
488 {
489 return $this->context;
490 }
491
497 public function setContext(Context $context)
498 {
499 $this->context = $context;
500 }
501
502 public function getLicense(): License
503 {
504 if (!$this->license)
505 {
506 $this->license = new License();
507 }
508
509 return $this->license;
510 }
511
520 public static function getConnection($name = "")
521 {
522 $pool = Application::getInstance()->getConnectionPool();
523 return $pool->getConnection($name);
524 }
525
531 public function getCache()
532 {
533 return Data\Cache::createInstance();
534 }
535
541 public function getManagedCache()
542 {
543 if ($this->managedCache == null)
544 {
545 $this->managedCache = new Data\ManagedCache();
546 }
547
548 return $this->managedCache;
549 }
550
556 public function getTaggedCache()
557 {
558 if ($this->taggedCache == null)
559 {
560 $this->taggedCache = new Data\TaggedCache();
561 }
562
563 return $this->taggedCache;
564 }
565
566 final public function getSessionLocalStorageManager(): Data\LocalStorage\SessionLocalStorageManager
567 {
569 }
570
571 final public function getLocalSession($name): Data\LocalStorage\SessionLocalStorage
572 {
573 return $this->sessionLocalStorageManager->get($name);
574 }
575
576 final public function getKernelSession(): SessionInterface
577 {
579 }
580
581 final public function getSession(): SessionInterface
582 {
583 return $this->session;
584 }
585
587 {
589 }
590
596 public static function getUserTypeManager()
597 {
598 global $USER_FIELD_MANAGER;
599 return $USER_FIELD_MANAGER;
600 }
601
607 public static function isUtfMode()
608 {
609 static $isUtfMode = null;
610 if ($isUtfMode === null)
611 {
612 $isUtfMode = Config\Configuration::getValue("utf_mode");
613 if ($isUtfMode === null)
614 $isUtfMode = false;
615 }
616 return $isUtfMode;
617 }
618
624 public static function getDocumentRoot()
625 {
626 static $documentRoot = null;
627 if ($documentRoot != null)
628 return $documentRoot;
629
630 $context = Application::getInstance()->getContext();
631 if ($context != null)
632 {
633 $server = $context->getServer();
634 if ($server != null)
635 return $documentRoot = $server->getDocumentRoot();
636 }
637
639 }
640
646 public static function getPersonalRoot()
647 {
648 static $personalRoot = null;
649 if ($personalRoot != null)
650 return $personalRoot;
651
652 $context = Application::getInstance()->getContext();
653 if ($context != null)
654 {
655 $server = $context->getServer();
656 if ($server != null)
657 return $personalRoot = $server->getPersonalRoot();
658 }
659
660 return $_SERVER["BX_PERSONAL_ROOT"] ?? '/bitrix';
661 }
662
666 public static function resetAccelerator()
667 {
668 if (defined("BX_NO_ACCELERATOR_RESET"))
669 return;
670
671 $fl = Config\Configuration::getValue("no_accelerator_reset");
672 if ($fl)
673 return;
674
675 if (function_exists("accelerator_reset"))
676 accelerator_reset();
677 elseif (function_exists("wincache_refresh_if_changed"))
678 wincache_refresh_if_changed();
679 }
680
688 public function addBackgroundJob(callable $job, array $args = [], $priority = self::JOB_PRIORITY_NORMAL)
689 {
690 $this->backgroundJobs->insert([$job, $args], $priority);
691
692 return $this;
693 }
694
695 protected function runBackgroundJobs()
696 {
697 $lastException = null;
698 $exceptionHandler = $this->getExceptionHandler();
699
700 //jobs can be added from jobs
701 while($this->backgroundJobs->valid())
702 {
703 //clear the queue
704 $jobs = [];
705 foreach ($this->backgroundJobs as $job)
706 {
707 $jobs[] = $job;
708 }
709
710 //do job
711 foreach ($jobs as $job)
712 {
713 try
714 {
715 call_user_func_array($job[0], $job[1]);
716 }
717 catch (\Throwable $exception)
718 {
719 $lastException = $exception;
720 $exceptionHandler->writeToLog($exception);
721 }
722 }
723 }
724
725 if ($lastException !== null)
726 {
727 throw $lastException;
728 }
729 }
730
735 public function isInitialized()
736 {
737 return $this->initialized;
738 }
739}
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