1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
application.php
См. документацию.
1<?php
2
9
10namespace Bitrix\Main;
11
12use Bitrix\Main\Config\Configuration;
13use Bitrix\Main\DI\ServiceLocator;
14use Bitrix\Main\Messenger\Config\WorkerRunMode;
15use Bitrix\Main\Messenger\Internals\Worker;
16use Bitrix\Main\Routing\CompileCache;
17use Bitrix\Main\Routing\Route;
18use Bitrix\Main\Routing\Router;
19use Bitrix\Main\Routing\RoutingConfigurator;
20use Bitrix\Main\Session\CompositeSessionManager;
21use Bitrix\Main\Session\KernelSessionProxy;
22use Bitrix\Main\Session\SessionConfigurationResolver;
23use Bitrix\Main\Session\SessionInterface;
24use Bitrix\Main\Session\Handlers\CookieSessionHandler;
25
29abstract class Application
30{
32 const JOB_PRIORITY_LOW = 50;
33
37 protected static $instance;
38 protected bool $initialized = false;
39 protected bool $terminating = false;
45 protected $context;
47 protected $router;
49 protected $currentRoute;
54 protected $connectionPool;
59 protected $managedCache;
64 protected $taggedCache;
66 protected $session;
68 protected $kernelSession;
73 /*
74 * @var \SplPriorityQueue
75 */
76 protected $backgroundJobs;
78 protected $license;
79
83 protected function __construct()
84 {
85 ServiceLocator::getInstance()->registerByGlobalSettings();
86 $this->backgroundJobs = new \SplPriorityQueue();
88 $this->initializeCache();
91 }
92
98 public static function getInstance()
99 {
100 if (!isset(static::$instance))
101 {
102 static::$instance = new static();
103 }
104 return static::$instance;
105 }
106
110 public static function hasInstance()
111 {
112 return isset(static::$instance);
113 }
114
119 public function initializeBasicKernel()
120 {
121 }
122
129 {
130 $this->initializeContext($params);
131
132 if (!$this->initialized)
133 {
134 $this->initializeSessions();
135 $this->initializeSessionLocalStorage();
136
137 $this->initialized = true;
138 }
139 }
140
141 private function initializeSessions()
142 {
143 $resolver = new SessionConfigurationResolver(Configuration::getInstance());
144 $resolver->resolve();
145
146 $this->session = $resolver->getSession();
147 $this->kernelSession = $resolver->getKernelSession();
148
149 $this->compositeSessionManager = new CompositeSessionManager(
150 $this->kernelSession,
151 $this->session
152 );
153 }
154
155 private function initializeSessionLocalStorage()
156 {
157 $cacheEngine = Data\Cache::createCacheEngine();
158 if ($cacheEngine instanceof Data\LocalStorage\Storage\CacheEngineInterface)
159 {
160 $localSessionStorage = new Data\LocalStorage\Storage\CacheStorage($cacheEngine);
161 }
162 else
163 {
164 $localSessionStorage = new Data\LocalStorage\Storage\NativeSessionStorage(
165 $this->getSession()
166 );
167 }
168
169 $this->sessionLocalStorageManager = new Data\LocalStorage\SessionLocalStorageManager($localSessionStorage);
170 $configLocalStorage = Config\Configuration::getValue("session_local_storage") ?: [];
171 if (isset($configLocalStorage['ttl']))
172 {
173 $this->sessionLocalStorageManager->setTtl($configLocalStorage['ttl']);
174 }
175 }
176
180 public function getRouter(): Router
181 {
182 if ($this->router === null)
183 {
184 $this->router = $this->initializeRouter();
185 }
186
187 return $this->router;
188 }
189
193 public function setRouter(Router $router): void
194 {
195 $this->router = $router;
196 }
197
201 public function getCurrentRoute(): Route
202 {
203 return $this->currentRoute;
204 }
205
206 public function hasCurrentRoute(): bool
207 {
208 return isset($this->currentRoute);
209 }
210
214 public function setCurrentRoute(Route $currentRoute): void
215 {
216 $this->currentRoute = $currentRoute;
217 }
218
219 protected function initializeRouter()
220 {
221 $routes = new RoutingConfigurator();
222 $router = new Router();
223 $routes->setRouter($router);
224
225 $this->setRouter($router);
226
227 // files with routes
228 $files = [];
229
230 // user files
231 $routingConfig = Configuration::getInstance()->get('routing');
232 $documentRoot = $this->context->getServer()->getDocumentRoot();
233
234 if (!empty($routingConfig['config']))
235 {
236 $fileNames = $routingConfig['config'];
237
238 foreach ($fileNames as $fileName)
239 {
240 foreach (['local', 'bitrix'] as $vendor)
241 {
242 $filename = $documentRoot . '/' . $vendor . '/routes/' . basename($fileName);
243
244 if (file_exists($filename))
245 {
246 $files[] = $filename;
247 }
248 }
249 }
250 }
251
252 // system files
253 if (file_exists($documentRoot . '/bitrix/routes/web_bitrix.php'))
254 {
255 $files[] = $documentRoot . '/bitrix/routes/web_bitrix.php';
256 }
257
258 foreach ($files as $file)
259 {
260 $callback = include $file;
261 $callback($routes);
262 }
263
264 $router->releaseRoutes();
265
266 // cache for route compiled data
268
269 return $router;
270 }
271
277 abstract protected function initializeContext(array $params);
278
283 abstract public function start();
284
291 public function run()
292 {
293 }
294
305 public function end($status = 0, Response $response = null)
306 {
307 if ($response === null)
308 {
309 //use default response
310 $response = $this->context->getResponse();
311
312 //it's possible to have open buffers
313 $content = '';
314 $n = ob_get_level();
315 while (($c = ob_get_clean()) !== false && $n > 0)
316 {
317 $content .= $c;
318 $n--;
319 }
320
321 if ($content <> '')
322 {
323 $response->appendContent($content);
324 }
325 }
326
328
329 //this is the last point of output - all output below will be ignored
330 $response->send();
331
332 $this->terminate($status);
333 }
334
336 {
338 if (!($kernelSession instanceof KernelSessionProxy) && $kernelSession->isStarted())
339 {
340 //save session data in cookies
341 $handler = $kernelSession->getSessionHandler();
342 if ($handler instanceof CookieSessionHandler)
343 {
344 if ($response instanceof HttpResponse)
345 {
346 $handler->setResponse($response);
347 }
348 }
349 $kernelSession->save();
350 }
351 }
352
360 public function terminate($status = 0)
361 {
362 if ($this->terminating)
363 {
364 // recursion control
365 return;
366 }
367
368 $this->terminating = true;
369
370 //old kernel staff
371 \CMain::RunFinalActionsInternal();
372
373 //Release session
374 session_write_close();
375
376 $pool = $this->getConnectionPool();
377
378 $pool->useMasterOnly(true);
379
380 $this->runBackgroundJobs();
381
382 $pool->useMasterOnly(false);
383
385
386 $pool->disconnect();
387
388 exit($status);
389 }
390
416 protected function initializeExceptionHandler()
417 {
418 $exceptionHandler = new Diag\ExceptionHandler();
419
420 $exceptionHandling = Config\Configuration::getValue("exception_handling");
421 if ($exceptionHandling == null)
422 {
423 $exceptionHandling = [];
424 }
425
426 if (!isset($exceptionHandling["debug"]) || !is_bool($exceptionHandling["debug"]))
427 {
428 $exceptionHandling["debug"] = false;
429 }
430 $exceptionHandler->setDebugMode($exceptionHandling["debug"]);
431
432 if (!empty($exceptionHandling['track_modules']) && is_array($exceptionHandling['track_modules']))
433 {
434 $exceptionHandler->setTrackModules($exceptionHandling['track_modules']);
435 }
436
437 if (isset($exceptionHandling["handled_errors_types"]) && is_int($exceptionHandling["handled_errors_types"]))
438 {
439 $exceptionHandler->setHandledErrorsTypes($exceptionHandling["handled_errors_types"]);
440 }
441
442 if (isset($exceptionHandling["exception_errors_types"]) && is_int($exceptionHandling["exception_errors_types"]))
443 {
444 $exceptionHandler->setExceptionErrorsTypes($exceptionHandling["exception_errors_types"]);
445 }
446
447 if (isset($exceptionHandling["ignore_silence"]) && is_bool($exceptionHandling["ignore_silence"]))
448 {
449 $exceptionHandler->setIgnoreSilence($exceptionHandling["ignore_silence"]);
450 }
451
452 if (isset($exceptionHandling["assertion_throws_exception"]) && is_bool($exceptionHandling["assertion_throws_exception"]))
453 {
454 $exceptionHandler->setAssertionThrowsException($exceptionHandling["assertion_throws_exception"]);
455 }
456
457 if (isset($exceptionHandling["assertion_error_type"]) && is_int($exceptionHandling["assertion_error_type"]))
458 {
459 $exceptionHandler->setAssertionErrorType($exceptionHandling["assertion_error_type"]);
460 }
461
462 $exceptionHandler->initialize(
463 [$this, "createExceptionHandlerOutput"],
464 [$this, "createExceptionHandlerLog"]
465 );
466
467 ServiceLocator::getInstance()->addInstance('exceptionHandler', $exceptionHandler);
468 }
469
471 {
472 $exceptionHandling = Config\Configuration::getValue("exception_handling");
473
474 if (!is_array($exceptionHandling) || !isset($exceptionHandling["log"]) || !is_array($exceptionHandling["log"]))
475 {
476 return null;
477 }
478
479 $options = $exceptionHandling["log"];
480
481 $log = null;
482
483 if (!empty($options["class_name"]))
484 {
485 if (!empty($options["extension"]) && !extension_loaded($options["extension"]))
486 {
487 return null;
488 }
489
490 if (!empty($options["required_file"]) && ($requiredFile = Loader::getLocal($options["required_file"])) !== false)
491 {
492 require_once($requiredFile);
493 }
494
495 $className = $options["class_name"];
496 if (!class_exists($className))
497 {
498 return null;
499 }
500
501 $log = new $className();
502 }
503 elseif (isset($options["settings"]) && is_array($options["settings"]))
504 {
505 $log = new Diag\FileExceptionHandlerLog();
506 }
507 else
508 {
509 return null;
510 }
511
512 $log->initialize(
513 isset($options["settings"]) && is_array($options["settings"]) ? $options["settings"] : []
514 );
515
516 return $log;
517 }
518
520 {
521 return new Diag\ExceptionHandlerOutput();
522 }
523
527 protected function createDatabaseConnection()
528 {
529 $this->connectionPool = new Data\ConnectionPool();
530 }
531
532 protected function initializeCache()
533 {
534 //TODO: Should be transfered to where GET parameter is defined in future
535 //magic parameters: show cache usage statistics
536 $show_cache_stat = "";
537 if (isset($_GET["show_cache_stat"]))
538 {
539 $show_cache_stat = (strtoupper($_GET["show_cache_stat"]) == "Y" ? "Y" : "");
540 @setcookie("show_cache_stat", $show_cache_stat, false, "/");
541 }
542 elseif (isset($_COOKIE["show_cache_stat"]))
543 {
544 $show_cache_stat = $_COOKIE["show_cache_stat"];
545 }
546 Data\Cache::setShowCacheStat($show_cache_stat === "Y");
547
548 if (isset($_GET["clear_cache_session"]))
549 {
550 Data\Cache::setClearCacheSession($_GET["clear_cache_session"] === 'Y');
551 }
552 if (isset($_GET["clear_cache"]))
553 {
554 Data\Cache::setClearCache($_GET["clear_cache"] === 'Y');
555 }
556 }
557
558 protected function initializeMessengerWorker(): void
559 {
560 $config = Config\Configuration::getValue('messenger');
561
562 if (!$config)
563 {
564 $config = ['run_mode' => WorkerRunMode::BackgroundInWeb->value];
565 }
566
567 if (!isset($config['run_mode']))
568 {
569 $config['run_mode'] = WorkerRunMode::BackgroundInWeb->value;
570 }
571
572 if ($config['run_mode'] === WorkerRunMode::Cli->value)
573 {
574 return;
575 }
576
577 $worker = new Worker();
578
579 $this->addBackgroundJob([$worker, 'process']);
580 }
581
585 public function getExceptionHandler()
586 {
587 return ServiceLocator::getInstance()->get('exceptionHandler');
588 }
589
595 public function getConnectionPool()
596 {
598 }
599
605 public function getContext()
606 {
607 return $this->context;
608 }
609
615 public function setContext(Context $context)
616 {
617 $this->context = $context;
618 }
619
620 public function getLicense(): License
621 {
622 if (!$this->license)
623 {
624 $this->license = new License();
625 }
626
627 return $this->license;
628 }
629
638 public static function getConnection($name = "")
639 {
640 $pool = Application::getInstance()->getConnectionPool();
641 return $pool->getConnection($name);
642 }
643
649 public function getCache()
650 {
651 return Data\Cache::createInstance();
652 }
653
659 public function getManagedCache()
660 {
661 if ($this->managedCache == null)
662 {
663 $this->managedCache = new Data\ManagedCache();
664 }
665
666 return $this->managedCache;
667 }
668
674 public function getTaggedCache()
675 {
676 if ($this->taggedCache == null)
677 {
678 $this->taggedCache = new Data\TaggedCache();
679 }
680
681 return $this->taggedCache;
682 }
683
684 final public function getSessionLocalStorageManager(): Data\LocalStorage\SessionLocalStorageManager
685 {
687 }
688
689 final public function getLocalSession($name): Data\LocalStorage\SessionLocalStorage
690 {
691 return $this->sessionLocalStorageManager->get($name);
692 }
693
694 final public function getKernelSession(): SessionInterface
695 {
697 }
698
699 final public function getSession(): SessionInterface
700 {
701 return $this->session;
702 }
703
708
714 public static function getUserTypeManager()
715 {
716 global $USER_FIELD_MANAGER;
717 return $USER_FIELD_MANAGER;
718 }
719
726 public static function isUtfMode()
727 {
728 return true;
729 }
730
736 public static function getDocumentRoot()
737 {
738 static $documentRoot = null;
739 if ($documentRoot != null)
740 {
741 return $documentRoot;
742 }
743
744 $context = Application::getInstance()->getContext();
745 if ($context != null)
746 {
747 $server = $context->getServer();
748 if ($server != null)
749 {
750 return $documentRoot = $server->getDocumentRoot();
751 }
752 }
753
755 }
756
762 public static function getPersonalRoot()
763 {
764 static $personalRoot = null;
765 if ($personalRoot != null)
766 {
767 return $personalRoot;
768 }
769
770 $context = Application::getInstance()->getContext();
771 if ($context != null)
772 {
773 $server = $context->getServer();
774 if ($server != null)
775 {
776 return $personalRoot = $server->getPersonalRoot();
777 }
778 }
779
780 return $_SERVER["BX_PERSONAL_ROOT"] ?? '/bitrix';
781 }
782
786 public static function resetAccelerator(string $filename = null)
787 {
788 if (defined("BX_NO_ACCELERATOR_RESET"))
789 {
790 return;
791 }
792
793 if (Config\Configuration::getValue("no_accelerator_reset"))
794 {
795 return;
796 }
797
798 if (function_exists("opcache_reset"))
799 {
800 if ($filename !== null)
801 {
802 opcache_invalidate($filename);
803 }
804 else
805 {
806 opcache_reset();
807 }
808 }
809 }
810
818 public function addBackgroundJob(callable $job, array $args = [], $priority = self::JOB_PRIORITY_NORMAL)
819 {
820 $this->backgroundJobs->insert([$job, $args], $priority);
821
822 return $this;
823 }
824
825 protected function runBackgroundJobs()
826 {
827 $lastException = null;
828 $exceptionHandler = $this->getExceptionHandler();
829
830 //jobs can be added from jobs
831 while ($this->backgroundJobs->valid())
832 {
833 //clear the queue
834 $jobs = [];
835 foreach ($this->backgroundJobs as $job)
836 {
837 $jobs[] = $job;
838 }
839
840 //do job
841 foreach ($jobs as $job)
842 {
843 try
844 {
845 call_user_func_array($job[0], $job[1]);
846 }
847 catch (\Throwable $exception)
848 {
849 $lastException = $exception;
850 $exceptionHandler->writeToLog($exception);
851 }
852 }
853 }
854
855 if ($lastException !== null)
856 {
857 throw $lastException;
858 }
859 }
860
865 public function isInitialized()
866 {
867 return $this->initialized;
868 }
869}
__construct()
Определения application.php:83
handleResponseBeforeSend(Response $response)
Определения application.php:335
setContext(Context $context)
Определения application.php:615
getCompositeSessionManager()
Определения application.php:704
static resetAccelerator(string $filename=null)
Определения application.php:786
const JOB_PRIORITY_NORMAL
Определения application.php:31
createExceptionHandlerOutput()
Определения application.php:519
initializeMessengerWorker()
Определения application.php:558
getManagedCache()
Определения application.php:659
setCurrentRoute(Route $currentRoute)
Определения application.php:214
static getDocumentRoot()
Определения application.php:736
hasCurrentRoute()
Определения application.php:206
initializeExceptionHandler()
Определения application.php:416
bool $initialized
Определения application.php:38
createDatabaseConnection()
Определения application.php:527
const JOB_PRIORITY_LOW
Определения application.php:32
initializeCache()
Определения application.php:532
initializeBasicKernel()
Определения application.php:119
$backgroundJobs
Определения application.php:76
addBackgroundJob(callable $job, array $args=[], $priority=self::JOB_PRIORITY_NORMAL)
Определения application.php:818
static getUserTypeManager()
Определения application.php:714
getConnectionPool()
Определения application.php:595
isInitialized()
Определения application.php:865
bool $terminating
Определения application.php:39
$sessionLocalStorageManager
Определения application.php:72
getExceptionHandler()
Определения application.php:585
initializeRouter()
Определения application.php:219
static hasInstance()
Определения application.php:110
getSessionLocalStorageManager()
Определения application.php:684
terminate($status=0)
Определения application.php:360
static isUtfMode()
Определения application.php:726
getTaggedCache()
Определения application.php:674
$connectionPool
Определения application.php:54
initializeContext(array $params)
static getInstance()
Определения application.php:98
getKernelSession()
Определения application.php:694
static getPersonalRoot()
Определения application.php:762
$compositeSessionManager
Определения application.php:70
createExceptionHandlerLog()
Определения application.php:470
getCurrentRoute()
Определения application.php:201
static $instance
Определения application.php:37
getLocalSession($name)
Определения application.php:689
setRouter(Router $router)
Определения application.php:193
static getConnection($name="")
Определения application.php:638
runBackgroundJobs()
Определения application.php:825
end($status=0, Response $response=null)
Определения application.php:305
initializeExtendedKernel(array $params)
Определения application.php:128
static finalize()
Определения managedcache.php:155
static getDocumentRoot()
Определения loader.php:254
static getLocal($path, $root=null)
Определения loader.php:572
Определения response.php:5
static handle($files, $router)
Определения compilecache.php:23
$options
Определения commerceml2.php:49
$content
Определения commerceml.php:144
$filename
Определения file_edit.php:47
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
global $USER_FIELD_MANAGER
Определения attempt.php:6
$_SERVER["DOCUMENT_ROOT"]
Определения cron_frame.php:9
foreach(['Bitrix\\Main'=> '/lib', 'Psr\\Container'=> '/vendor/psr/container/src', 'Psr\\Log'=> '/vendor/psr/log/src', 'Psr\\Http\\Message'=> '/vendor/psr/http-message/src', 'Psr\\Http\\Client'=> '/vendor/psr/http-client/src', 'Http\\Promise'=> '/vendor/php-http/promise/src', 'PHPMailer\\PHPMailer'=> '/vendor/phpmailer/phpmailer/src', 'GeoIp2'=> '/vendor/geoip2/geoip2/src', 'MaxMind\\Db'=> '/vendor/maxmind-db/reader/src/MaxMind/Db', 'PhpParser'=> '/vendor/nikic/php-parser/lib/PhpParser', 'Recurr'=> '/vendor/simshaun/recurr/src/Recurr',] as $namespace=> $namespacePath) $documentRoot
Определения autoload.php:27
$status
Определения session.php:10
$name
Определения menu_edit.php:35
Определения culture.php:9
Определения aliases.php:105
$files
Определения mysql_to_pgsql.php:30
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$config
Определения quickway.php:69
$fileName
Определения quickway.php:305
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$response
Определения result.php:21
$n
Определения update_log.php:107