• Модуль: abtest
  • Путь к файлу: ~/bitrix/modules/abtest/lib/helper.php
  • Класс: BitrixABTestHelper
  • Вызов: Helper::getContext
static function getContext()
{
	global $USER, $APPLICATION;

	static $context;

	if (!defined('SITE_ID') || !SITE_ID)
		return null;

	if (empty($context))
	{
		$activeTest = Helper::getActiveTest();

		$isAbtestAdmin = is_object($USER) && $USER->canDoOperation('view_other_settings');
		if ($isAbtestAdmin && !empty($_SESSION['ABTEST_MODE']))
		{
			if ($_SESSION['ABTEST_MODE'] == 'reset')
			{
				if (!empty($activeTest))
					$context = Helper::context($activeTest, 'N');

				unset($_SESSION['ABTEST_MODE']);
			}
			else if (preg_match('/^(d+)|(A|B|N)$/', $_SESSION['ABTEST_MODE'], $matches))
			{
				if (!empty($activeTest) && $activeTest['ID'] == intval($matches[1]))
				{
					$context = Helper::context($activeTest, $matches[2]);

					unset($_SESSION['ABTEST_MODE']);
				}
				else
				{
					$abtest = ABTestTable::getList(array(
						'filter' => array('=ID' => intval($matches[1]), 'ENABLED' => 'Y')
					))->fetch();

					if (!empty($abtest) && $abtest['SITE_ID'] == SITE_ID)
						$context = Helper::context($abtest, $matches[2]);
				}
			}
		}

		$cookieValue = $APPLICATION->get_cookie('ABTEST_'.SITE_ID);

		if (empty($context) && !empty($activeTest))
		{
			$abtest = $activeTest;

			if (!empty($cookieValue))
			{
				if (preg_match('/^'.intval($abtest['ID']).'|(A|B|N)$/i', $cookieValue, $matches))
					$section = $matches[1];
			}

			if (empty($section))
			{
				$dice = mt_rand(1, 100);

				if ($dice <= intval($abtest['PORTION'])/2)
					$section = 'A';
				else if ($dice <= intval($abtest['PORTION']))
					$section = 'B';
				else
					$section = 'N';
			}

			$context = Helper::context($abtest, $section);
		}

		if (empty($activeTest) || $activeTest['ID'] == $context['abtest'])
		{
			$newValue = empty($activeTest) ? null : sprintf('%u|%s', $context['abtest'], $context['section']);
			if (!(empty($cookieValue) && empty($newValue)) && $cookieValue !== $newValue)
			{
				$cookie = new MainWebCookie(sprintf('ABTEST_%s', SITE_ID), $newValue);

				MainContext::getCurrent()->getResponse()->addCookie($cookie);
			}
		}
	}

	return $context;
}