Your IP : 18.223.125.111


Current Path : /var/www/axolotl/data/www/arhangelsk.axolotls.ru/a537b/
Upload File :
Current File : /var/www/axolotl/data/www/arhangelsk.axolotls.ru/a537b/interface.tar

favorite_act.php000064400000005357147732346240007751 0ustar00<?
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
define("NO_AGENT_CHECK", true);
define("DisableEventsCheck", true);

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

if($USER->IsAuthorized() && check_bitrix_sessid())
{
	CUtil::JSPostUnescape();

	$res = false;
	$uid = $USER->GetID();
	$now = $DB->GetNowFunction();
	global $adminMenu;

	switch ($_REQUEST["act"])
	{
		case  'add':

			$arFields = array(
							"MODIFIED_BY"	=>	$uid,
							"CREATED_BY"	=>	$uid,
							"USER_ID"	=>	$uid,
							"LANGUAGE_ID"	=> LANGUAGE_ID,
							"~TIMESTAMP_X"	=> $now,
							"COMMON"	=>	"N",
							"~DATE_CREATE"	=>	$now,
							);

			$_REQUEST["addurl"] = CHTTP::urlDeleteParams($_REQUEST["addurl"], array("IFRAME", "IFRAME_TYPE"));
			if(isset($_REQUEST["menu_id"]))
			{
				$arFields["MENU_ID"] = $_REQUEST["menu_id"];

				if (isset($_REQUEST['module_id']))
					$arFields["MODULE_ID"] = $_REQUEST["module_id"];

				$favMenu = new CBXFavAdmMenu;
				$menuItem = $favMenu->GetMenuItem($arFields["MENU_ID"], $adminMenu->aGlobalMenu);
				$arFields["NAME"] = $menuItem["text"] ? htmlspecialcharsback($menuItem["text"]) : $_REQUEST["name"];

				if(isset($_REQUEST["addurl"]) && !empty($_REQUEST["addurl"]))
					$arFields["URL"] = $_REQUEST["addurl"];
				elseif(isset($menuItem["url"]) && !empty($menuItem["url"]))
					$arFields["URL"] = htmlspecialcharsback($menuItem["url"]);
			}
			else
			{
				$arFields["NAME"] =	htmlspecialcharsback($_REQUEST["name"]);

				if(isset($_REQUEST["addurl"]) && !empty($_REQUEST["addurl"]))
					$arFields["URL"] =	$_REQUEST["addurl"];
			}

			$arFields["NAME"] = trim($arFields["NAME"]);

			$id = CFavorites::Add($arFields,true);

			if($id)
			{
				$favMenu = new CBXFavAdmMenu;
				$res = $favMenu->GenerateMenuHTML($id);
			}

			break;

		case 'delete':

			if(!isset($_REQUEST["id"]) || !$_REQUEST["id"])
				break;

			$dbFav = CFavorites::GetByID($_REQUEST["id"]);

			while ($arFav = $dbFav->GetNext())
				if($arFav["USER_ID"]==$uid)
					$res = CFavorites::Delete($_REQUEST["id"]);

			if($res)
			{
				$favMenu = new CBXFavAdmMenu;
				$res = $favMenu->GenerateMenuHTML();
			}


			break;

		case 'get_list':

			$dbFav = CFavorites::GetList();
			while ($arFav = $dbFav->GetNext())
				if($uid == $arFav["USER_ID"] || $arFav["COMMON"]=="Y")
					$res[] = array("NAME" => $arFav["NAME"], "URL" => $arFav["URL"], "LANGUAGE_ID" => $arFav["LANGUAGE_ID"]);

			if($res)
				$res = CUtil::PhpToJSObject($res);

			break;

		case 'get_menu_html':

			$favMenu = new CBXFavAdmMenu;
			$res = $favMenu->GenerateMenuHTML();

			break;

	}

	echo $res;
}

require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
?>
admin_viewtabcontrol.php000064400000004411147732346240011503 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

/*View Tab Control*/
class CAdminViewTabControl
{
	var $name;
	var $tabs;
	var $selectedTab;
	var $tabIndex = 0;

	public function __construct($name, $tabs)
	{
		//array(array("DIV"=>"", "TAB"=>"", "ICON"=>, "TITLE"=>"", "ONSELECT"=>"javascript"), ...)
		$this->tabs = $tabs;
		$this->name = $name;
		if(isset($_REQUEST[$this->name."_active_tab"]))
			$this->selectedTab = $_REQUEST[$this->name."_active_tab"];
		else
		{
			foreach($tabs as $tab)
			{
				if (
					!isset($tab["VISIBLE"])
					|| $tab["VISIBLE"]
				)
				{
					$this->selectedTab = $tab["DIV"];
					break;
				}
			}
		}
	}

	function Begin()
	{
		echo '
<div class="adm-detail-subtabs-block">
';
		$i = 0;
		foreach($this->tabs as $tab)
		{
			$bSelected = ($tab["DIV"] == $this->selectedTab);
			echo '<span class="adm-detail-subtabs'.($bSelected? " adm-detail-subtab-active":"").'" id="view_tab_'.$tab["DIV"].'" onclick="'.$this->name.'.SelectTab(\''.$tab["DIV"].'\');" title="'.$tab["TITLE"].'"'.(isset($tab["VISIBLE"]) && !$tab["VISIBLE"] ? ' style="display: none;"' : '').'>'.$tab["TAB"].'</span>'."\n";
			$i++;
		}
echo '</div>';
	}

	function BeginNextTab()
	{
		//end previous tab
		$this->EndTab();

		if($this->tabIndex >= count($this->tabs))
			return;

		echo '
<div id="'.$this->tabs[$this->tabIndex]["DIV"].'"'.($this->tabs[$this->tabIndex]["DIV"] <> $this->selectedTab ? ' style="display:none;"':'').'>
	<div class="adm-detail-content-item-block-view-tab">
	<div class="adm-detail-title-view-tab">'.$this->tabs[$this->tabIndex]["TITLE"].'</div>
';
		$this->tabIndex++;
	}

	function EndTab()
	{
		if($this->tabIndex < 1 || $this->tabIndex > count($this->tabs))
			return;
		echo '
	</div>
</div>
';
	}

	function End()
	{
		$this->EndTab();
		echo '
<script type="text/javascript">
';
		$s = "";
		foreach($this->tabs as $tab)
		{
			$s .= ($s <> ""? ", ":"").
			"{".
			"'DIV': '".$tab["DIV"]."' ".
			($tab["ONSELECT"] <> ""? ", 'ONSELECT': '".CUtil::JSEscape($tab["ONSELECT"])."'":"").
			"}";
		}
		echo 'var '.$this->name.' = new BX.adminViewTabControl(['.$s.']); ';

		if(defined('BX_PUBLIC_MODE') && BX_PUBLIC_MODE == 1)
		{
			echo 'window.'.$this->name.'.setPublicMode(true); ';
		}

		echo '</script>';
	}
}
navigation.php000066400000013456147732346240007443 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

if($this->bPostNavigation)
	$nav_func_name = 'PostAdminList';
else
	$nav_func_name = 'GetAdminList';

$sQueryString = CUtil::JSEscape($strNavQueryString);
$sJSUrlPath = htmlspecialcharsbx(CUtil::JSEscape($sUrlPath));

$showWait = "BX.addClass(this,'adm-nav-page-active');setTimeout(BX.delegate(function(){BX.addClass(this,'adm-nav-page-loading');this.innerHTML='';},this),500);";

if($this->NavRecordCount>0)
{
?>
<div class="adm-navigation">
	<div class="adm-nav-pages-block">
<?
	if($this->NavPageNomer > 1)
	{
?>
		<a class="adm-nav-page adm-nav-page-prev" href="javascript:void(0)" onclick="<?echo $this->table_id?>.<?=$nav_func_name?>('<?echo $sJSUrlPath.'?PAGEN_'.$this->NavNum.'='.($this->NavPageNomer-1).'&amp;SIZEN_'.$this->NavNum.'='.$this->NavPageSize.$sQueryString;?>');<?=$showWait?>"></a>
<?
	}
	else //$this->NavPageNomer > 1
	{
?>
		<span class="adm-nav-page adm-nav-page-prev"></span>
<?
	} //$this->NavPageNomer > 1

	//$NavRecordGroup = $this->nStartPage;
	$NavRecordGroup = 1;
	while($NavRecordGroup <= $this->NavPageCount)
	{
		if($NavRecordGroup == $this->NavPageNomer)
		{
?>
		<span class="adm-nav-page-active adm-nav-page"><?=$NavRecordGroup?></span>
<?
		}
		else // ($NavRecordGroup == $this->NavPageNomer):
		{
?>
		<a href="javascript:void(0)" onclick="<?=$this->table_id?>.<?=$nav_func_name?>('<?=$sJSUrlPath.'?PAGEN_'.$this->NavNum.'='.$NavRecordGroup.'&amp;SIZEN_'.$this->NavNum.'='.$this->NavPageSize.$sQueryString?>');<?=$showWait?>" class="adm-nav-page"><?=$NavRecordGroup?></a>
<?
		} //endif($NavRecordGroup == $this->NavPageNomer):

		if($NavRecordGroup == 2 && $this->nStartPage > 3)
		{
			if($this->nStartPage - $NavRecordGroup > 1)
			{
				$middlePage = ceil(($this->nStartPage + $NavRecordGroup)/2);
?>
		<a href="javascript:void(0)" onclick="<?=$this->table_id?>.<?=$nav_func_name?>('<?=$sJSUrlPath.'?PAGEN_'.$this->NavNum.'='.$middlePage.'&amp;SIZEN_'.$this->NavNum.'='.$this->NavPageSize.$sQueryString?>');<?=$showWait?>" class="adm-nav-page-separator"><?=$middlePage?></a>
<?
			}
			$NavRecordGroup = $this->nStartPage;
		}
		elseif($NavRecordGroup == $this->nEndPage && $this->nEndPage < $this->NavPageCount - 2)
		{
			if( $this->NavPageCount-1 - $NavRecordGroup > 1)
			{
				$middlePage = floor(($this->NavPageCount + $this->nEndPage - 1)/2);
?>
		<a href="javascript:void(0)" onclick="<?=$this->table_id?>.<?=$nav_func_name?>('<?=$sJSUrlPath.'?PAGEN_'.$this->NavNum.'='.$middlePage.'&amp;SIZEN_'.$this->NavNum.'='.$this->NavPageSize.$sQueryString?>');<?=$showWait?>" class="adm-nav-page-separator"><?=$middlePage?></a>
<?
			}

			$NavRecordGroup = $this->NavPageCount-1;
		}
		else
		{
			$NavRecordGroup++;
		}

	} // endwhile;//($NavRecordGroup <= $this->nEndPage):

	if($this->NavPageNomer < $this->NavPageCount)
	{
?>
		<a class="adm-nav-page adm-nav-page-next" href="javascript:void(0)" onclick="<?echo $this->table_id?>.<?=$nav_func_name?>('<?echo $sJSUrlPath.'?PAGEN_'.$this->NavNum.'='.($this->NavPageNomer+1).'&amp;SIZEN_'.$this->NavNum.'='.$this->NavPageSize.$sQueryString;?>');<?=$showWait?>"></a>
<?
	}
	else //($this->NavPageNomer < $this->NavPageCount):
	{
?>
		<span class="adm-nav-page adm-nav-page-next"></span>
<?
	} //endif; //($this->NavPageNomer < $this->NavPageCount):
?>
	</div>
<?
	if($this->NavRecordCount>0)
	{
?>
	<div class="adm-nav-pages-total-block"><?
	echo $title." ".(($this->NavPageNomer-1)*$this->NavPageSize+1)." &ndash; ";
	if($this->NavPageNomer <> $this->NavPageCount)
		echo($this->NavPageNomer * $this->NavPageSize);
	else
		echo($this->NavRecordCount);
	echo " ".GetMessage("navigation_records_of")." ".$this->NavRecordCount;
	?></div>
<?
	} // endif($this->NavRecordCount>0);
?>
	<div class="adm-nav-pages-number-block"><span class="adm-nav-pages-number">
		<?if(!$this->NavRecordCountChangeDisable)
		{
			?><span class="adm-nav-pages-number-text"><?echo GetMessage("navigation_records")?></span><span class="adm-select-wrap"><select name="" class="adm-select" onchange="if(this[selectedIndex].value=='0'){<?echo $this->table_id?>.<?=$nav_func_name?>('<?echo $sJSUrlPath."?PAGEN_".$this->NavNum."=1&amp;SHOWALL_".$this->NavNum."=1".CUtil::addslashes($strNavQueryString);?>');}else{<?echo $this->table_id?>.<?=$nav_func_name?>('<?echo $sJSUrlPath."?PAGEN_".$this->NavNum."=1&amp;SHOWALL_".$this->NavNum."=0"."&amp;SIZEN_".$this->NavNum."="?>'+this[selectedIndex].value+'<?echo CUtil::addslashes($strNavQueryString);?>');}">
<?
	$aSizes = array(10, 20, 50, 100, 200, 500);
	if($this->nInitialSize > 0 && !in_array($this->nInitialSize, $aSizes))
		array_unshift($aSizes, $this->nInitialSize);
	$reqSize = intval($_REQUEST["SIZEN_".$this->NavNum]);
	if($reqSize > 0 && !in_array($reqSize, $aSizes))
		array_unshift($aSizes, $reqSize);
	foreach($aSizes as $size)
	{
?>
		<option value="<?echo $size?>"<?if($this->NavPageSize == $size)echo ' selected="selected"'?>><?echo $size?></option>
<?
	} //endforeach;

	if($this->bShowAll)
	{
?>
			<option value="0"<?if($this->NavShowAll) echo ' selected="selected"'?>><?echo GetMessage("navigation_records_all")?></option>
<?
	} //endif;
?>
	</select><?}?></span></span></div>
</div>
<?
} //endif; //$this->NavRecordCount>0;

if (!isset($_REQUEST['admin_history']))
{
?>
	<script type="text/javascript">
		var topWindow = (window.BX||window.parent.BX).PageObject.getRootWindow();
		var parentWindow = (window.BX||window.parent.BX).PageObject.getParentWindowOfCurrentHost(window);
		topWindow.BX.adminHistory.put('<?=CUtil::JSEscape($sUrlPath.'?PAGEN_'.$this->NavNum.'='.$this->NavPageNomer.'&amp;SIZEN_'.$this->NavNum.'='.$this->NavPageSize.$strNavQueryString)?>', topWindow.BX.proxy((topWindow.<?=$this->table_id?>)?parentWindow.<?=$this->table_id?>.<?=$nav_func_name?>:<?=$this->table_id?>.<?=$nav_func_name?>, window.<?=$this->table_id?>), ['mode', 'table_id']);</script>
	<?
} //endif;
?>user_options.php000066400000002045147732346240010025 0ustar00<?
##############################################
# Bitrix Site Manager                        #
# Copyright (c) 2002-2007 Bitrix             #
# http://www.bitrixsoft.com                  #
# mailto:admin@bitrixsoft.com                #
##############################################

define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
define("BX_SECURITY_SESSION_READONLY", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

if($USER->IsAuthorized() && check_bitrix_sessid())
{
	if($_GET["action"] == "delete" && $_GET["c"] <> "" && $_GET["n"] <> "")
		CUserOptions::DeleteOption($_GET["c"], $_GET["n"], ($_GET["common"]=="Y" && $GLOBALS["USER"]->CanDoOperation('edit_other_settings')));
	if(is_array($_REQUEST["p"]))
	{
		$arOptions = $_REQUEST["p"];
		CUtil::decodeURIComponent($arOptions);
		CUserOptions::SetOptionsFromArray($arOptions);
	}
}
echo "OK";
require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
?>
admin_calendar.php000064400000017040147732346240010214 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

class CAdminCalendar
{
	const PERIOD_EMPTY = "NOT_REF";
	const PERIOD_DAY = "day";
	const PERIOD_WEEK = "week";
	const PERIOD_MONTH = "month";
	const PERIOD_QUARTER = "quarter";
	const PERIOD_YEAR = "year";
	const PERIOD_EXACT = "exact";
	const PERIOD_BEFORE = "before";
	const PERIOD_AFTER = "after";
	const PERIOD_INTERVAL = "interval";

	private static function InitPeriodList($arPeriodParams = array())
	{
		$arPeriod = array(
			self::PERIOD_EMPTY => GetMessage("admin_lib_calend_no_period"),
			self::PERIOD_DAY => GetMessage("admin_lib_calend_day"),
			self::PERIOD_WEEK => GetMessage("admin_lib_calend_week"),
			self::PERIOD_MONTH => GetMessage("admin_lib_calend_month"),
			self::PERIOD_QUARTER => GetMessage("admin_lib_calend_quarter"),
			self::PERIOD_YEAR => GetMessage("admin_lib_calend_year"),
			self::PERIOD_EXACT => GetMessage("admin_lib_calend_exact"),
			self::PERIOD_BEFORE => GetMessage("admin_lib_calend_before"),
			self::PERIOD_AFTER => GetMessage("admin_lib_calend_after"),
			self::PERIOD_INTERVAL => GetMessage("admin_lib_calend_interval")
		);

		if (empty($arPeriodParams) || !is_array($arPeriodParams))
			return $arPeriod;

		$arReturnPeriod = array();

		foreach ($arPeriodParams as $periodName => $lPhrase)
		{
			if (isset($arPeriod[$periodName]))
				$arReturnPeriod[$periodName] = $lPhrase;
			elseif (isset($arPeriod[$arPeriodParams[$periodName]]))
				$arReturnPeriod[$arPeriodParams[$periodName]] = $arPeriod[$arPeriodParams[$periodName]];
		}

		if (empty($arReturnPeriod))
			$arReturnPeriod = $arPeriod;
		return $arReturnPeriod;
	}

	public static function ShowScript()
	{
		CJSCore::Init(array('date'));
	}

	public static function Calendar($sFieldName, $sFromName="", $sToName="", $bTime=false)
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		ob_start();
		$APPLICATION->IncludeComponent('bitrix:main.calendar', '', array(
			'RETURN' => 'Y',
			'SHOW_INPUT' => 'N',
			'INPUT_NAME' => $sFieldName,
			'SHOW_TIME' => $bTime ? 'Y' : 'N'
		), null, array('HIDE_ICONS' => 'Y'));
		$res = ob_get_contents();
		ob_end_clean();

		return $res;
	}

	public static function CalendarDate($sFieldName, $sValue="", $size="10", $bTime=false)
	{
		// component can't set 'size' param
		return '
	<div class="adm-input-wrap adm-input-wrap-calendar">
		<input class="adm-input adm-input-calendar" type="text" name="'.$sFieldName.'" size="'.(intval($size)+3).'" value="'.htmlspecialcharsbx($sValue).'">
		<span class="adm-calendar-icon" title="'.GetMessage("admin_lib_calend_title").'" onclick="BX.calendar({node:this, field:\''.$sFieldName.'\', form: \'\', bTime: '.($bTime ? 'true' : 'false').', bHideTime: false});"></span>
	</div>';

	}

	/**
	 * @param string $sFromName
	 * @param string $sToName
	 * @param string $sFromVal
	 * @param string $sToVal
	 * @param bool $bSelectShow
	 * @param int $size
	 * @param bool $bTime
	 * @param bool|array $arPeriod
	 * @param string $periodValue
	 * @return string
	 */
	public static function CalendarPeriodCustom($sFromName, $sToName, $sFromVal="", $sToVal="", $bSelectShow=false, $size=10, $bTime=false, $arPeriod = false, $periodValue = '')
	{
		$arPeriodList = self::InitPeriodList($arPeriod);

		return self::GetPeriodHtml($sFromName, $sToName, $sFromVal, $sToVal, $bSelectShow, $size, $bTime, $arPeriodList, $periodValue);
	}

	/**
	 * @param string $sFromName
	 * @param string $sToName
	 * @param string $sFromVal
	 * @param string $sToVal
	 * @param bool $bSelectShow
	 * @param int $size
	 * @param bool $bTime
	 * @return string
	 */
	public static function CalendarPeriod($sFromName, $sToName, $sFromVal="", $sToVal="", $bSelectShow=false, $size=10, $bTime=false)
	{
		$arPeriodList = self::InitPeriodList();

		return self::GetPeriodHtml($sFromName, $sToName, $sFromVal, $sToVal, $bSelectShow, $size, $bTime, $arPeriodList);
	}

	/**
	 * @param $sFromName
	 * @param $sToName
	 * @param string $sFromVal
	 * @param string $sToVal
	 * @param bool $bSelectShow
	 * @param int $size
	 * @param bool $bTime
	 * @param $arPeriod
	 * @param string $periodValue
	 * @return string
	 */
	private static function GetPeriodHtml($sFromName, $sToName, $sFromVal="", $sToVal="", $bSelectShow=false, $size = 10, $bTime=false, $arPeriod, $periodValue = '')
	{
		$size = (int)$size;

		$s = '
		<div class="adm-calendar-block adm-filter-alignment">
			<div class="adm-filter-box-sizing">';

		if($bSelectShow)
		{
			$sPeriodName = $sFromName."_FILTER_PERIOD";
			$sDirectionName = $sFromName."_FILTER_DIRECTION";

			$arDirection = array(
				"previous"=>GetMessage("admin_lib_calend_previous"),
				"current"=>GetMessage("admin_lib_calend_current"),
				"next"=>GetMessage("admin_lib_calend_next")
			);

			$s .= '<span class="adm-select-wrap adm-calendar-period" ><select class="adm-select adm-calendar-period" id="'.$sFromName.'_calendar_period" name="'.$sPeriodName.'" onchange="BX.CalendarPeriod.OnChangeP(this);" title="'.GetMessage("admin_lib_calend_period_title").'">';

			$currentPeriod = '';
			if (isset($GLOBALS[$sPeriodName]))
				$currentPeriod = (string)$GLOBALS[$sPeriodName];
			$periodValue = (string)$periodValue;
			if ($periodValue != '')
				$currentPeriod = $periodValue;
			foreach($arPeriod as $k => $v)
			{
					$k = ($k != "NOT_REF" ? $k : "");
					$s .= '<option value="'.$k.'"'.(($currentPeriod != '' && $currentPeriod == $k) ? " selected":"").'>'.$v.'</option>';
			}
			unset($currentPeriod);

			$s .='</select></span>';

			$currentDirection = '';
			if (isset($GLOBALS[$sDirectionName]))
				$currentDirection = (string)$GLOBALS[$sDirectionName];
			$s .= '<span class="adm-select-wrap adm-calendar-direction" style="display: none;"><select class="adm-select adm-calendar-direction" id="'.$sFromName.'_calendar_direct" name="'.$sDirectionName.'" onchange="BX.CalendarPeriod.OnChangeD(this);"  title="'.GetMessage("admin_lib_calend_direct_title").'">';
			foreach($arDirection as $k => $v)
					$s .= '<option value="'.$k.'"'.($currentDirection == $k ? " selected":"").'>'.$v.'</option>';
			unset($currentDirection);

			$s .='</select></span>';
		}

		$s .=''.
		'<div class="adm-input-wrap adm-calendar-inp adm-calendar-first" style="display: '.($bSelectShow ? 'none' : 'inline-block').';">'.
			'<input type="text" class="adm-input adm-calendar-from" id="'.$sFromName.'_calendar_from" name="'.$sFromName.'" size="'.($size+5).'" value="'.htmlspecialcharsbx($sFromVal).'">'.
			'<span class="adm-calendar-icon" title="'.GetMessage("admin_lib_calend_title").'" onclick="BX.calendar({node:this, field:\''.$sFromName.'\', form: \'\', bTime: '.($bTime ? 'true' : 'false').', bHideTime: false});"></span>'.
		'</div>
		<span class="adm-calendar-separate" style="display: '.($bSelectShow ? 'none' : 'inline-block').'"></span>'.
		'<div class="adm-input-wrap adm-calendar-second" style="display: '.($bSelectShow ? 'none' : 'inline-block').';">'.
			'<input type="text" class="adm-input adm-calendar-to" id="'.$sToName.'_calendar_to" name="'.$sToName.'" size="'.($size+5).'" value="'.htmlspecialcharsbx($sToVal).'">'.
			'<span class="adm-calendar-icon" title="'.GetMessage("admin_lib_calend_title").'" onclick="BX.calendar({node:this, field:\''.$sToName.'\', form: \'\', bTime: '.($bTime ? 'true' : 'false').', bHideTime: false});"></span>'.
		'</div>'.
		'<script type="text/javascript">
			window["'.$sFromName.'_bTime"] = '.($bTime ? "true" : "false").';';

		if($bSelectShow)
			$s .='BX.CalendarPeriod.Init(BX("'.$sFromName.'_calendar_from"), BX("'.$sToName.'_calendar_to"), BX("'.$sFromName.'_calendar_period"));';

		$s .='
		</script>
		</div>
		</div>';

		return $s;
	}
}
prolog_main_admin.php000066400000043525147732346240010762 0ustar00<?
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2013 Bitrix
 */

/**
 * Bitrix vars
 * @global CUser $USER
 * @global CMain $APPLICATION
 * @global CAdminPage $adminPage
 * @global CAdminMenu $adminMenu
 * @global CAdminMainChain $adminChain
 * @global string $SiteExpireDate
 */

if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

IncludeModuleLangFile(__FILE__);

if($APPLICATION->GetTitle() == '')
	$APPLICATION->SetTitle(GetMessage("MAIN_PROLOG_ADMIN_TITLE"));

$aUserOpt = CUserOptions::GetOption("admin_panel", "settings");
$aUserOptGlobal = CUserOptions::GetOption("global", "settings");

$isSidePanel = (isset($_REQUEST["IFRAME"]) && $_REQUEST["IFRAME"] === "Y");

$adminPage->Init();
$adminMenu->Init($adminPage->aModules);

$bShowAdminMenu = !empty($adminMenu->aGlobalMenu);

global $adminSidePanelHelper;
if (!is_object($adminSidePanelHelper))
{
	require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");
	$adminSidePanelHelper = new CAdminSidePanelHelper();
}

$aOptMenuPos = array();
if($bShowAdminMenu && class_exists("CUserOptions"))
{
	$aOptMenuPos = CUserOptions::GetOption("admin_menu", "pos", array());
	$bOptMenuMinimized = $aOptMenuPos['ver'] == 'off';
}

if (!defined('ADMIN_SECTION_LOAD_AUTH') || !ADMIN_SECTION_LOAD_AUTH):
	$direction = "";
	$direct = CLanguage::GetByID(LANGUAGE_ID);
	$arDirect = $direct->Fetch();
	if($arDirect["DIRECTION"] == "N")
		$direction = ' dir="rtl"';

?>
<!DOCTYPE html>
<html<?=$aUserOpt['fix'] == 'on' ? ' class="adm-header-fixed"' : ''?><?=$direction?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?=htmlspecialcharsbx(LANG_CHARSET)?>">
<meta name="viewport" content="initial-scale=1.0, width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?$adminPage->ShowTitle()?> - <?echo COption::GetOptionString("main","site_name", $_SERVER["SERVER_NAME"])?></title>
<?
else:
?>
<script type="text/javascript">
<?
	if ($aUserOpt['fix'] == 'on'):
?>
document.documentElement.className = 'adm-header-fixed';
<?
	endif;
?>
window.document.title = '<?$adminPage->ShowJsTitle()?> - <?echo CUtil::JSEscape(COption::GetOptionString("main","site_name", $_SERVER["SERVER_NAME"]));?>';
</script>
<?
endif;

$APPLICATION->AddBufferContent(array($adminPage, "ShowCSS"));
echo $adminPage->ShowScript();
$APPLICATION->ShowHeadStrings();
$APPLICATION->ShowHeadScripts();
?>
<script type="text/javascript">
BX.message({MENU_ENABLE_TOOLTIP: <?=($aUserOptGlobal['start_menu_title'] <> 'N' ? 'true' : 'false')?>});
BX.InitializeAdmin();

var topWindow = BX.PageObject.getRootWindow();
if (!topWindow.window["adminSidePanel"] || !BX.is_subclass_of(topWindow.window["adminSidePanel"], topWindow.BX.adminSidePanel))
{
	topWindow.window["adminSidePanel"] = new topWindow.BX.adminSidePanel();
}
</script>
<?
if (!defined('ADMIN_SECTION_LOAD_AUTH') || !ADMIN_SECTION_LOAD_AUTH):
?>
</head>
<body id="bx-admin-prefix">
<!--[if lte IE 7]>
<style type="text/css">
#bx-panel {display:none !important;}
.adm-main-wrap { display:none !important; }
</style>
<div id="bx-panel-error">
<?echo GetMessage("admin_panel_browser")?>
</div><![endif]-->
<?
endif;
if(($adminHeader = getLocalPath("php_interface/admin_header.php", BX_PERSONAL_ROOT)) !== false)
	include($_SERVER["DOCUMENT_ROOT"].$adminHeader);

?>
	<table class="adm-main-wrap">
		<?if (!$isSidePanel):?>
		<tr>
			<td class="adm-header-wrap" colspan="2">
<?

require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/top_panel.php");
require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/favorite_menu.php");

?>
			</td>
		</tr>
		<?endif;?>
		<tr>
<?

	CJSCore::Init(array('admin_interface'));
	$APPLICATION->AddHeadScript('/bitrix/js/main/dd.js');

	$aActiveSection = $adminMenu->ActiveSection();

	if(isset($GLOBALS["BX_FAVORITE_MENU_ACTIVE_ID"]) && $GLOBALS["BX_FAVORITE_MENU_ACTIVE_ID"])
		$openedSection ="desktop";
	else
		$openedSection = CUtil::JSEscape($aActiveSection["menu_id"]);

	$favOptions = CUserOptions::GetOption('favorite', 'favorite_menu', array("stick" => "N"));
	$stick = (array_key_exists("global_menu_desktop", $adminMenu->aActiveSections) || $openedSection =="desktop" ) ? "Y" : "N";
	if($stick <> $favOptions["stick"])
	{
		CUserOptions::SetOption('favorite', 'favorite_menu', array('stick' => $stick));
	}
?>
			<?if (!$isSidePanel):?>
			<td class="adm-left-side-wrap" id="menu_mirrors_cont">

<script type="text/javascript">
BX.adminMenu.setMinimizedState(<?=$bOptMenuMinimized ? 'true' : 'false'?>);
BX.adminMenu.setActiveSection('<?=$openedSection?>');
BX.adminMenu.setOpenedSections('<?=CUtil::JSEscape($adminMenu->GetOpenedSections());?>');
</script>
				<div class="adm-left-side<?=$bOptMenuMinimized ? ' adm-left-side-wrap-close' : ''?>"<?if(intval($aOptMenuPos["width"]) > 0) echo ' style="width:'.($bOptMenuMinimized ? 15 : intval($aOptMenuPos["width"])).'px" data-width="'.intval($aOptMenuPos["width"]).'"'?> id="bx_menu_panel"><div class="adm-menu-wrapper<?=$bOptMenuMinimized ? ' adm-main-menu-close' : ''?>" style="overflow:hidden; min-width:300px;">
						<div class="adm-main-menu">
<?
	$menuScripts = "";

	foreach($adminMenu->aGlobalMenu as $menu):

		$menuClass = "adm-main-menu-item adm-".$menu["menu_id"];

		if(($menu["items_id"] == $aActiveSection["items_id"] && $openedSection !="desktop" )|| $menu["menu_id"] == $openedSection)
			$menuClass .=' adm-main-menu-item-active';

		if ($menu['url']):
?>
						<a href="<?=htmlspecialcharsbx($menu["url"])?>" class="adm-default <?=$menuClass?>" onclick="BX.adminMenu.GlobalMenuClick('<?echo $menu["menu_id"]?>'); return false;" onfocus="this.blur();" id="global_menu_<?echo $menu["menu_id"]?>">
							<div class="adm-main-menu-item-icon"></div>
							<div class="adm-main-menu-item-text"><?echo htmlspecialcharsbx($menu["text"])?></div>
							<div class="adm-main-menu-hover"></div>
						</a>
<?
		else:
?>
						<span class="adm-default <?=$menuClass?>" onclick="BX.adminMenu.GlobalMenuClick('<?echo $menu["menu_id"]?>'); return false;" id="global_menu_<?echo $menu["menu_id"]?>">
							<div class="adm-main-menu-item-icon"></div>
							<div class="adm-main-menu-item-text"><?echo htmlspecialcharsbx($menu["text"])?></div>
							<div class="adm-main-menu-hover"></div>
						</span>
<?
		endif;
	endforeach;
?>
					</div>
					<div class="adm-submenu" id="menucontainer">
<?
		foreach($adminMenu->aGlobalMenu as $menu):

			if(
				(
					(
						$menu["menu_id"] == $aActiveSection["menu_id"]
						|| $menu["items_id"] == $aActiveSection["items_id"]

					)
					&& $openedSection !="desktop"
				)
				|| $menu["menu_id"] == $openedSection

			)
				$subMenuDisplay = "block";
			else
				$subMenuDisplay = "none";

?>
						<div class="adm-global-submenu<?=($subMenuDisplay == "block" ? " adm-global-submenu-active" : "")?>" id="global_submenu_<?echo $menu["menu_id"]?>">
<?
		if ($menu['menu_id'] == 'desktop')
		{
			require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/desktop_menu.php");

			$menu["text"] = $favMenuText;
			$menu["items"] = $favMenuItems;
		}
?>
							<div class="adm-submenu-items-wrap">
								<div class="adm-submenu-items-stretch-wrap" onscroll="BX.adminMenu.itemsStretchScroll()">
									<table class="adm-submenu-items-stretch">
										<tr>
											<td class="adm-submenu-items-stretch-cell">
												<div class="adm-submenu-items-block">
													<div class="adm-submenu-items-title adm-submenu-title-<?=$menu['menu_id']?>"><?=htmlspecialcharsbx($menu["text"])?></div>
													<div id='<?="_".$menu['items_id']?>'>
<?
		if(!empty($menu["items"]))
		{
			foreach($menu["items"] as $submenu)
			{
				$menuScripts .= $adminMenu->Show($submenu);
			}
		}
		elseif ($menu['menu_id'] == 'desktop')
			echo CBXFavAdmMenu::GetEmptyMenuHTML();

		if($menu['menu_id'] == 'desktop')
			echo CBXFavAdmMenu::GetMenuHintHTML(empty($menu["items"]));

?>
													</div>
												</div>
											</td>
										</tr>
									</table>
								</div>
							</div>
						</div>
<?
	endforeach;
?>
						<div class="adm-submenu-separator"></div>
<?
	if ($menuScripts != ""):
?>
<script type="text/javascript"><?=$menuScripts?></script>
<?
	endif;

	if(file_exists($_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/php_interface/this_site_logo.php"))
	{
		include($_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/php_interface/this_site_logo.php");
	}
?>
					</div>
				</div></div>
			</td>
			<?endif;?>
			<td class="adm-workarea-wrap <?=defined('BX_ADMIN_SECTION_404') && BX_ADMIN_SECTION_404 == 'Y' ? 'adm-404-error' : 'adm-workarea-wrap-top'?>">
				<div class="adm-workarea adm-workarea-page" id="adm-workarea">
<?
//wizard customization file
$bxProductConfig = array();
if(file_exists($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/.config.php"))
	include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/.config.php");

//Title
$curPage = $APPLICATION->GetCurPage(true);
if ($curPage != "/bitrix/admin/index.php")
{
	$currentFavId = null;
	$currentItemsId = '';

	if (!defined('BX_ADMIN_SECTION_404') || BX_ADMIN_SECTION_404 != 'Y')
	{
		if ($isSidePanel)
		{
			$requestUri = CHTTP::urlDeleteParams($_SERVER["REQUEST_URI"], array("IFRAME", "IFRAME_TYPE"));
			$currentFavId = CFavorites::getIDByUrl($requestUri);
		}
		else
		{
			$arLastItem = null;
			//Navigation chain
			$adminChain->Init();
			$arLastItem = $adminChain->Show();

			$currentFavId = CFavorites::GetIDByUrl($_SERVER["REQUEST_URI"]);
			$currentItemsId = '';
		}
	}
}

foreach (GetModuleEvents("main", "OnPrologAdminTitle", true) as $arEvent)
{
	$arPageParams = array();
	$arPageParams[] = $curPage;
	if (isset($_GET["pageid"]))
		$arPageParams[] = $_GET["pageid"];

	ExecuteModuleEventEx($arEvent, $arPageParams);
}

if ($curPage != "/bitrix/admin/index.php" && !$adminPage->isHideTitle())
{
	$isFavLink = !defined('BX_ADMIN_SECTION_404') || BX_ADMIN_SECTION_404 != 'Y';
	if ($adminSidePanelHelper->isPublicSidePanel())
	{
		$isFavLink = false;
	}
	?>
		<h1 class="adm-title" id="adm-title">
			<?$adminPage->ShowTitle()?>
			<?if($isFavLink):?>
			<a href="javascript:void(0)" class="adm-fav-link<?=$currentFavId>0?' adm-fav-link-active':''?>" onclick="
				BX.adminFav.titleLinkClick(this, <?=intval($currentFavId)?>, '<?=$currentItemsId?>')" title="
				<?= $currentFavId ? GetMessage("MAIN_PR_ADMIN_FAV_DEL") : GetMessage("MAIN_PR_ADMIN_FAV_ADD")?>"></a>
			<?endif;?>
			<a id="navchain-link" href="<?echo htmlspecialcharsbx($_SERVER["REQUEST_URI"])?>" title="
			<?echo GetMessage("MAIN_PR_ADMIN_CUR_LINK")?>"></a>
		</h1>
	<?
}

//Content

if($USER->IsAuthorized()):
	if(defined("DEMO") && DEMO == "Y"):
		$vendor = COption::GetOptionString("main", "vendor", "1c_bitrix");
		$delta = $SiteExpireDate-time();
		$daysToExpire = ($delta < 0? 0 : ceil($delta/86400));
		$bSaas = (COption::GetOptionString('main', '~SAAS_MODE', "N") == "Y");

		echo BeginNote('style="position: relative; top: -15px;"');
		if(isset($bxProductConfig["saas"])):
			if($bSaas)
			{
				$sWarnDate = COption::GetOptionString('main', '~support_finish_date');
				if (!empty($sWarnDate))
					$sWarnDate = ConvertTimeStamp(MakeTimeStamp($sWarnDate, 'YYYY-MM-DD'), "SHORT");

				if($daysToExpire > 0)
				{
					if($daysToExpire <= $bxProductConfig["saas"]["days_before_warning"])
					{
						$sWarn = $bxProductConfig["saas"]["warning"];
						$sWarn = str_replace("#RENT_DATE#", $sWarnDate, $sWarn);
						$sWarn = str_replace("#DAYS#", $daysToExpire, $sWarn);
						echo $sWarn;
					}
				}
				else
				{
					echo str_replace("#RENT_DATE#", $sWarnDate, $bxProductConfig["saas"]["warning_expired"]);
				}
			}
			else
			{
				if($daysToExpire > 0)
					echo str_replace("#DAYS#", $daysToExpire, $bxProductConfig["saas"]["trial"]);
				else
					echo $bxProductConfig["saas"]["trial_expired"];
			}
		else: //saas
?>
	<span class="required"><?echo GetMessage("TRIAL_ATTENTION") ?></span>
	<?echo GetMessage("TRIAL_ATTENTION_TEXT1_".$vendor) ?>
	<?if ($daysToExpire >= 0):?>
	<?echo GetMessage("TRIAL_ATTENTION_TEXT2") ?> <span class="required"><b><?echo $daysToExpire?></b></span> <?echo GetMessage("TRIAL_ATTENTION_TEXT3") ?>.
	<?else:?>
	<?echo GetMessage("TRIAL_ATTENTION_TEXT4_".$vendor) ?>
	<?endif;?>
	<?echo GetMessage("TRIAL_ATTENTION_TEXT5_".$vendor) ?>
<?
		endif; //saas
		echo EndNote();

	elseif(defined("TIMELIMIT_EDITION") && TIMELIMIT_EDITION == "Y"):
	
		$delta = $SiteExpireDate - time();
		$daysToExpire = ceil($delta / 86400);
		$sWarnDate = ConvertTimeStamp($SiteExpireDate, "SHORT");

		if ($daysToExpire >= 0 && $daysToExpire < 60)
		{
			echo BeginNote('style="position: relative; top: -15px;"');
			echo GetMessage("prolog_main_timelimit11", array(
				'#FINISH_DATE#' => $sWarnDate,
				'#DAYS_AGO#' => $daysToExpire,
				'#DAYS_AGO_TXT#' => ($daysToExpire == 0? GetMessage("prolog_main_today") : GetMessage('prolog_main_support_days', array('#N_DAYS_AGO#' => $daysToExpire))),
			));
			echo EndNote();
		}
		elseif ($daysToExpire < 0)
		{
			echo BeginNote('style="position: relative; top: -15px;"');
			echo GetMessage("prolog_main_timelimit12", array(
				'#FINISH_DATE#' => $sWarnDate,
				'#DAYS_AGO#' => ((14 - abs($daysToExpire) >= 0) ? (14 - abs($daysToExpire)) : 0),
			));
			echo EndNote();
		};

	elseif($USER->CanDoOperation('install_updates')):
		//show support ending warning

		$supportFinishDate = COption::GetOptionString('main', '~support_finish_date', '');
		if($supportFinishDate <> '' && is_array(($aSupportFinishDate=ParseDate($supportFinishDate, 'ymd'))))
		{
			$aGlobalOpt = CUserOptions::GetOption("global", "settings", array());
			if($aGlobalOpt['messages']['support'] <> 'N')
			{
				$supportFinishStamp = mktime(0,0,0, $aSupportFinishDate[1], $aSupportFinishDate[0], $aSupportFinishDate[2]);
				$supportDateDiff = ceil(($supportFinishStamp - time())/86400);

				$sSupportMess = '';
				$sSupWIT = " (<span onclick=\"BX.toggle(BX('supdescr'))\" style='border-bottom: 1px dashed #1c91e7; color: #1c91e7; cursor: pointer;'>".GetMessage("prolog_main_support_wit")."</span>)";

				if($supportDateDiff >= 0 && $supportDateDiff <= 30)
				{
					$sSupportMess = GetMessage("prolog_main_support11_l", array(
						'#FINISH_DATE#' => GetTime($supportFinishStamp),
						'#DAYS_AGO#' => ($supportDateDiff == 0? GetMessage("prolog_main_today") : GetMessage('prolog_main_support_days', array('#N_DAYS_AGO#'=>$supportDateDiff))),
						'#LICENSE_KEY#' => md5(LICENSE_KEY),
						'#WHAT_IS_IT#' => $sSupWIT,
						'#SUP_FINISH_DATE#' => GetTime(mktime(0,0,0, $aSupportFinishDate[1]+1, $aSupportFinishDate[0], $aSupportFinishDate[2])),
					));
				}
				elseif($supportDateDiff < 0 && $supportDateDiff >= -30)
				{
					$sSupportMess = GetMessage("prolog_main_support21_l", array(
						'#FINISH_DATE#' => GetTime($supportFinishStamp),
						'#DAYS_AGO#' => (-$supportDateDiff),
						'#LICENSE_KEY#' => md5(LICENSE_KEY),
						'#WHAT_IS_IT#' => $sSupWIT,
						'#SUP_FINISH_DATE#' => GetTime(mktime(0,0,0, $aSupportFinishDate[1]+1, $aSupportFinishDate[0], $aSupportFinishDate[2])),
					));
				}
				elseif($supportDateDiff < -30)
				{
					$sSupportMess = GetMessage("prolog_main_support31_l", array(
						'#FINISH_DATE#' => GetTime($supportFinishStamp),
						'#LICENSE_KEY#' => md5(LICENSE_KEY),
						'#WHAT_IS_IT#' => $sSupWIT,
					));
				}

				if($sSupportMess <> '')
				{
					$userOption = CUserOptions::GetOption("main", "admSupInf");
					if(time() > $userOption["showInformerDate"])
					{
						$prolongUrl = "/bitrix/admin/buy_support.php?lang=".LANGUAGE_ID;
						if(!in_array(LANGUAGE_ID, array("ru", "ua")) || IntVal(COption::GetOptionString("main", "~PARAM_PARTNER_ID")) <= 0)
						{
							require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/classes/general/update_client.php");
							$prolongUrl = "http://www.1c-bitrix.ru/buy_tmp/key_update.php?license_key=".md5(CUpdateClient::GetLicenseKey())."&tobasket=y&lang=".LANGUAGE_ID;
						}

						echo BeginNote('style="position: relative; top: -15px;"');
						?>
						<style>
							#menu-popup-prolong-popup .popup-window-hr { display:none;}
							#menu-popup-prolong-popup .menu-popup .menu-popup-item {min-width: 100px; margin-top: 7px;}
							#menu-popup-prolong-popup .menu-popup-item:hover {background-color: #fff !important;}
						</style>
						<script>
						function showProlongMenu(bindElement)
						{
							BX.PopupMenu.show("prolong-popup", bindElement, [
								{
									text : '<b><?=GetMessageJS("prolog_main_support_menu1")?></b>'
								},
								{
									text : '<?=GetMessageJS("prolog_main_support_menu2")?>',
									onclick : function() {prolongRemind('<?=AddToTimeStamp(array("DD" => 7));?>', this)}
								},
								{
									text : '<?=GetMessageJS("prolog_main_support_menu3")?>',
									onclick : function() {prolongRemind('<?=AddToTimeStamp(array("DD" => 14));?>', this)}
								},
								{
									text : '<?=GetMessageJS("prolog_main_support_menu4")?>',
									onclick : function() {prolongRemind('<?=AddToTimeStamp(array("MM" => 1));?>', this)}
								}
							],
							{
								offsetTop : 5,
								offsetLeft : 13,
								angle : true
							});

							return false;
						}

						function prolongRemind(tt, el)
						{
							BX.userOptions.save('main', 'admSupInf', 'showInformerDate', tt);
							el.popupWindow.close();
							BX.hide(BX('prolongmenu').parentNode);
						}
						</script>
						<div style="float: right; padding-left: 50px; margin-top: -5px; text-align: center;">
							<a href="<?=$prolongUrl?>" target="_blank" class="adm-btn adm-btn-save" style="margin-bottom: 4px;"><?=GetMessage("prolog_main_support_button_prolong")?></a><br />

							<a href="javascript:void(0)" id="prolongmenu" onclick="showProlongMenu(this)" style="color: #716536;"><?=GetMessage("prolog_main_support_button_no_prolong2")?></a>
						</div>
						<?=$sSupportMess;?>
						<div id="supdescr" style="display: none;"><br /><br /><b><?=GetMessage("prolog_main_support_wit_descr1")?></b><hr><?=GetMessage("prolog_main_support_wit_descr2_l".(IsModuleInstalled("intranet") ? "_cp" : ""))?></div>
						<?
						echo EndNote();
					}
				}
			}
		}
	endif; //defined("DEMO") && DEMO == "Y"

endif; //$USER->IsAuthorized()
?>
get_search.php000064400000011517147732346240007402 0ustar00<?
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
define("BX_SEARCH_ADMIN", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_js.php");

$start = getmicrotime();

$query = ltrim($_POST["q"]);
if(
	!empty($query)
	&& $_REQUEST["ajax_call"] === "y"
	&& CModule::IncludeModule("search")
):

CUtil::decodeURIComponent($query);

/**
 * @var CAdminPage $adminPage
 * @var CAdminMenu $adminMenu
 */
$adminPage->Init();
$adminMenu->Init($adminPage->aModules);

$arResult = array(
	"CATEGORIES"=>array(
		"global_menu_content"=>array("ITEMS"=>array(), "TITLE"=>GetMessage('admin_lib_menu_content')),
		"global_menu_services"=>array("ITEMS"=>array(), "TITLE"=>GetMessage('admin_lib_menu_services')),
		"global_menu_store"=>array("ITEMS"=>array(), "TITLE"=>GetMessage('admin_lib_menu_store')),
		"global_menu_statistics"=>array("ITEMS"=>array(), "TITLE"=>GetMessage('admin_lib_menu_stat')),
		"global_menu_settings"=>array("ITEMS"=>array(), "TITLE"=>GetMessage('admin_lib_menu_settings')),
	)
);

$arStemFunc = stemming_init(LANGUAGE_ID);

$arPhrase = stemming_split($query, LANGUAGE_ID);

$preg_template = "/(^|[^".$arStemFunc["pcre_letters"]."])(".str_replace("/", "\\/", implode("|", array_map('preg_quote', array_keys($arPhrase)))).")/i".BX_UTF_PCRE_MODIFIER;
$bFound  = false;

function GetStrings(&$item, $key, $p)
{
	global $arStemFunc, $arPhrase, $preg_template, $arResult, $bFound;

	$category = $p[0];
	$icon = $p[1];
	$arRes = null;

	if($item["url"] <> '')
	{
		$searchstring = '';
		if($item["text"])
		{
			if(preg_match_all($preg_template, ToUpper($item["text"]), $arMatches, PREG_OFFSET_CAPTURE))
			{
				$c = count($arMatches[2]);
				if(defined("BX_UTF"))
				{
					for($j = $c-1; $j >= 0; $j--)
					{
						$prefix = mb_substr($item["text"], 0, $arMatches[2][$j][1], 'latin1');
						$instr  = mb_substr($item["text"], $arMatches[2][$j][1], mb_strlen($arMatches[2][$j][0], 'latin1'), 'latin1');
						$suffix = mb_substr($item["text"], $arMatches[2][$j][1] + mb_strlen($arMatches[2][$j][0], 'latin1'), mb_strlen($item["text"], 'latin1'), 'latin1');
						$item["text"] = $prefix."<b>".$instr."</b>".$suffix;
					}
				}
				else
				{
					for($j = $c-1; $j >= 0; $j--)
					{
						$prefix = substr($item["text"], 0, $arMatches[2][$j][1]);
						$instr  = substr($item["text"], $arMatches[2][$j][1], strlen($arMatches[2][$j][0]));
						$suffix = substr($item["text"], $arMatches[2][$j][1]+strlen($arMatches[2][$j][0]));
						$item["text"] = $prefix."<b>".$instr."</b>".$suffix;
					}
				}
			}
			$searchstring .= $item["text"];
		}

		if($item["title"])
			$searchstring .= " ".$item["title"];

		if($item["keywords"])
			$searchstring .= " ".$item["keywords"];

		if($item["icon"]=='')
			$item["icon"] = $icon;

		if(preg_match_all($preg_template, ToUpper($searchstring), $arMatches, PREG_OFFSET_CAPTURE))
		{
			$ar = Array();
			foreach($arMatches[0] as $m)
				$ar[] = trim($m[0], " ,;>");
			if(count(array_unique($ar)) == count($arPhrase))
			{
				$arRes = array("NAME"=>$item["text"], "URL"=>$item["url"], "TITLE"=>$item["title"], "ICON"=>$item['icon']);
			}
		}
	}

	if(is_array($arRes))
	{
		if($item['category'] == '')
			$item['category'] = $category;

		if(!is_array($arResult["CATEGORIES"][$item['category']]))
		{
			$arResult["CATEGORIES"][$item['category']] = Array('TITLE'=>'', 'ITEMS'=>Array());
			if($item['category_name']!='')
				$arResult["CATEGORIES"][$item['category']]['TITLE'] = $item['category_name'];
		}
		$arResult["CATEGORIES"][$item['category']]["ITEMS"][] = $arRes;
		$bFound = true;
	}

	if(is_array($item["items"]))
		array_walk($item['items'], 'GetStrings', array($category, $item["icon"]));
}

foreach($adminMenu->aGlobalMenu as $menu_id => $menu)
	array_walk($menu['items'], 'GetStrings', array($menu_id, ''));


if($bFound)
{
?>
	<table class="adm-search-result">
		<?foreach($arResult["CATEGORIES"] as $category_id => $arCategory):
			if(count($arCategory["ITEMS"])==0)
				continue;
			?>
			<?foreach($arCategory["ITEMS"] as $i => $arItem):
				if($i>9)
					break;
				?>
			<tr onclick="window.location='<?=CUtil::JSEscape($arItem["URL"]);?>';">
				<?if($i == 0):?>
					<th>&nbsp;<?=$arCategory["TITLE"]?></th>
				<?else:?>
					<th>&nbsp;</th>
				<?endif?>
				<td class="adm-search-item" <?if($arItem["TITLE"]!='' && $arItem["TITLE"]!=$arItem["NAME"]):?>title="<?=$arItem["TITLE"]?>"<?endif?>>
					<a href="<?=$arItem["URL"]?>"><?if($arItem["ICON"]!=''):?><span class="adm-submenu-item-link-icon <?=$arItem["ICON"]?>"></span><?endif?><span class="adm-submenu-item-name-link-text"><?=$arItem["NAME"]?></span></a>
				</td>
			</tr>
			<?endforeach;?>
		<?endforeach;?>
	</table>
<?
}


endif;

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin_js.php");
?>admin_tabcontrol_drag.php000064400000017011147732346240011605 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

class CAdminTabControlDrag extends CAdminTabControl
{
	protected $moduleId;

	public function __construct($name, $tabs, $moduleId="", $bCanExpand = true, $bDenyAutosave = false)
	{
		parent::__construct($name, $tabs, $bCanExpand, $bDenyAutosave);
		$this->moduleId = $moduleId;
		\Bitrix\Main\Page\Asset::getInstance()->addJs("/bitrix/js/main/admin_dd.js");
	}

	function BeginNextTab($options = array())
	{
		if ($this->AUTOSAVE)
			$this->AUTOSAVE->Init();

		//end previous tab
		$this->EndTab();

		if($this->tabIndex >= count($this->tabs))
			return;

		$css = '';
		if ($this->tabs[$this->tabIndex]["DIV"] <> $this->selectedTab)
			$css .= 'display:none; ';

		echo '
<div class="adm-detail-content" id="'.$this->tabs[$this->tabIndex]["DIV"].'"'.($css != '' ? ' style="'.$css.'"' : '').'>';

		if (!empty($this->tabs[$this->tabIndex]["TITLE"]))
			echo '
	<div class="adm-detail-title">'.$this->tabs[$this->tabIndex]["TITLE"].'</div>';

		if ($this->tabs[$this->tabIndex]["IS_DRAGGABLE"] == "Y")
		{
			$arJsParams = array(
				"moduleId" => $this->moduleId,
				"optionName" => $this->getCurrentTabOptionName($this->tabIndex),
				"tabId" => $this->tabs[$this->tabIndex]["DIV"],
				"hidden" => $this->getTabHiddenBlocks($this->tabIndex)
			);
			echo '
			<script>
				BX.ready(function(){
					var orderObj = new BX.Admin.DraggableTab('.CUtil::PhpToJSObject($arJsParams).');
				});
			</script>';
		}

		$showWrap = $this->tabs[$this->tabIndex]["SHOW_WRAP"] == "N" ? false : true;
		echo '
	<div '.($showWrap ? 'class="adm-detail-content-item-block"' : '').'>
		<table class="adm-detail-content-table edit-table" id="'.$this->tabs[$this->tabIndex]["DIV"].'_edit_table">
			<tbody>
';
		if(array_key_exists("CUSTOM", $this->tabs[$this->tabIndex]) && $this->tabs[$this->tabIndex]["CUSTOM"] == "Y")
		{
			$this->customTabber->ShowTab($this->tabs[$this->tabIndex]["DIV"]);
			$this->tabIndex++;
			$this->BeginNextTab();
		}
		elseif(array_key_exists("CONTENT", $this->tabs[$this->tabIndex]))
		{
			echo $this->tabs[$this->tabIndex]["CONTENT"];
			$this->tabIndex++;
			$this->BeginNextTab();
		}
		else
		{
			$this->tabIndex++;
		}
	}

	function ShowTabButtons()
	{
		$s = '';
		if (!$this->bPublicMode)
		{
			if(count($this->tabs) > 1 && $this->bCanExpand/* || $this->AUTOSAVE*/)
			{
				$s .= '<div class="adm-detail-title-setting" onclick="'.$this->name.'.ToggleTabs();" title="'.GetMessage("admin_lib_expand_tabs").'" id="'.$this->name.'_expand_link"><span class="adm-detail-title-setting-btn adm-detail-title-expand"></span></div>';
			}
		}
		return $s;
	}

	function getCurrentTabOptionName($tabIdx)
	{
		return $this->name."_".$this->tabs[$tabIdx]["DIV"];
	}

	function getTabSettings($tabIdx)
	{
		if (isset($this->tabs[$tabIdx]["SETTINGS"]))
			return $this->tabs[$tabIdx]["SETTINGS"];

		$tabSettings = CUserOptions::getOption($this->moduleId, $this->getCurrentTabOptionName($tabIdx));

		$tabSettings["order"] = isset($tabSettings["order"]) ? $tabSettings["order"] : array();
		if (!empty($tabSettings["order"]))
			$tabSettings["order"] = explode(",", $tabSettings["order"]);

		$tabSettings["hidden"] = isset($tabSettings["hidden"]) ? $tabSettings["hidden"] : array();
		if (!empty($tabSettings["hidden"]))
			$tabSettings["hidden"] = explode(",", $tabSettings["hidden"]);

		$this->tabs[$tabIdx]["SETTINGS"] = $tabSettings;
		return $tabSettings;
	}

	function getCurrentTabBlocksOrder($defaultBlocksOrder = array())
	{
		$tabSettings = $this->getTabSettings($this->tabIndex-1);
		$blocksOrder = $tabSettings["order"];

		if (is_array($defaultBlocksOrder) && !empty($defaultBlocksOrder))
		{
			if (empty($blocksOrder))
			{
				$blocksOrder = $defaultBlocksOrder;
			}
			else
			{
				foreach($blocksOrder as $key => $blockCode)
				{
					if (!in_array($blockCode, $defaultBlocksOrder))
						unset($blocksOrder[$key]);
				}
				$blocksOrder = array_unique(array_merge($blocksOrder, $defaultBlocksOrder));
			}
		}

		return $blocksOrder;
	}

	function getTabHiddenBlocks($tabIdx)
	{
		$tabSettings = $this->getTabSettings($tabIdx);
		$hiddenBlocks = $tabSettings["hidden"];
		return is_array($hiddenBlocks) ? $hiddenBlocks : array();
	}

	function DraggableBlocksStart()
	{
		echo '<div data-role="dragObj" data-onlydest="Y" style="height:5px;width:100%"></div>';
	}

	function DraggableBlockBegin($title, $dataId = "")
	{
		echo '
		<div class="adm-container-draggable'.(in_array($dataId, $this->getTabHiddenBlocks($this->tabIndex-1)) ? ' hidden' : '').'" data-role="dragObj" data-id="'.$dataId.'">
			<div class="adm-bus-statusorder">
				<div class="adm-bus-component-container">
					<div class="adm-bus-component-title-container draggable">
						<div class="adm-bus-component-title-icon"></div>
						<div class="adm-bus-component-title">'.$title.'</div>
						<div class="adm-bus-component-title-icon-turn" data-role="toggleObj"></div>'.
			//'<div class="adm-bus-component-title-icon-close"></div>'
			'</div>
					<div class="adm-bus-component-content-container">
						<div class="adm-bus-table-container">';
	}

	function DraggableBlockEnd()
	{
		echo '			</div>
					</div>
				</div>
			</div>
		</div>';
	}
}


/**
 * Class CAdminDraggableBlockEngine
 * Create custom Draggable blocks for CAdminTabControlDrag
 */
class CAdminDraggableBlockEngine
{
	protected $id;
	protected $engines = array();
	protected $args = array();

	/**
	* CAdminDraggableBlockEngine constructor.
	* @param string $id identifier
	* @param array $args
	*/
	public function __construct($id, $args = array())
	{
		$this->id = $id;
		$this->args = $args;

		foreach (GetModuleEvents("main", $this->id, true) as $arEvent)
		{
			$res = ExecuteModuleEventEx($arEvent, array($args));

			if (is_array($res))
				$this->engines[$res["BLOCKSET"]] = $res;
		}
	}

	/**
	 * @param array $args
	 */
	public function setArgs($args = array())
	{
		$this->args = $args;
	}

	/**
	 * @return bool
 	 */
	public function check()
	{
		$result = True;

		foreach ($this->engines as $value)
		{
			if (array_key_exists("check", $value))
			{
				$resultTmp = call_user_func_array($value["check"], array($this->args));

				if ($result && !$resultTmp)
					$result = false;
			}
		}

		return $result;
	}

	/**
	 * @return bool
	 */
	public function action()
	{
		$result = True;

		foreach ($this->engines as $value)
		{
			if (array_key_exists("action", $value))
			{
				$resultTmp = call_user_func_array($value["action"], array($this->args));

				if ($result && !$resultTmp)
					$result = False;
			}
		}

		return $result;
	}

	/**
	 * @return array
	 */
	public function getBlocksBrief()
	{
		$blocks = array();

		foreach ($this->engines as $key => $value)
		{
			if (array_key_exists("getBlocksBrief", $value))
			{
				 $tmp = call_user_func_array($value["getBlocksBrief"], array($this->args));

				if (is_array($tmp))
					$blocks = $blocks + $tmp;
			}
		}

		return $blocks;
	}

	/**
	 * @param string $blockCode
	 * @param string $selectedTab
     * @return string
     */
	public function getBlockContent($blockCode, $selectedTab)
	{
		$result = '';

		foreach ($this->engines as $key => $value)
			if (array_key_exists("getBlockContent", $value))
				 $result .= call_user_func_array($value["getBlockContent"], array($blockCode, $selectedTab, $this->args));

		return $result;
	}

	/**
	 * @return string
 	 */
	public function getScripts()
	{
		$result = '';

		foreach ($this->engines as $key => $value)
		{
			if (array_key_exists("getScripts", $value))
				 $result .= call_user_func_array($value["getScripts"], array($this->args));
		}

		return $result;
	}
}
init_jspopup.php000064400000001265147732346240010020 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

function JSPopupRedirectHandler(&$url, $skip_security_check)
{
	$a = new CAutoSave();
	$a->Reset();

	if(preg_match("#^/bitrix/admin/#", $url))
	{
		ob_end_clean();
		echo '<script type="text/javascript">top.BX.WindowManager.Get().Close(); '.(!$_REQUEST['subdialog'] ? 'top.BX.reload(true);' : '').'</script>';
		die();
	}
	else
	{
		ob_end_clean();
		echo '<script type="text/javascript">top.BX.WindowManager.Get().Close(); '.(!$_REQUEST['subdialog'] ? 'top.BX.reload(\''.CUtil::JSEscape($url).'\', true);' : '').'</script>';
		die();
	}
}

AddEventHandler('main', 'OnBeforeLocalRedirect', 'JSPopupRedirectHandler');
?>admin_lib.php000066400000214161147732346240007216 0ustar00<?
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2015 Bitrix
 */

if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

IncludeModuleLangFile(__FILE__);

define("ADMIN_THEMES_PATH", "/bitrix/themes");

class CAdminPage
{
	var $aModules = array();
	var $bInit = false;
	var $publicMode = false;

	private $isHideTitle = false;

	public function __construct()
	{
		if (defined("PUBLIC_MODE") && PUBLIC_MODE == 1)
		{
			$this->publicMode = true;
		}
	}

	public function Init()
	{
		if($this->bInit)
			return;
		$this->bInit = true;

		$module_list = CModule::GetList();
		while($module = $module_list->Fetch())
			$this->aModules[] = $module["ID"];
	}

	public function ShowTitle()
	{
		global $APPLICATION;
		$APPLICATION->AddBufferContent(array(&$this, "GetTitle"));
	}

	public function ShowJsTitle()
	{
		global $APPLICATION;
		$APPLICATION->AddBufferContent(array(&$this, "GetJsTitle"));
	}

	function GetTitle()
	{
		global $APPLICATION;
		return htmlspecialcharsex($APPLICATION->GetTitle(false, true));
	}

	public function isHideTitle()
	{
		return $this->isHideTitle;
	}

	public function hideTitle()
	{
		$this->isHideTitle = true;
	}

	function GetJsTitle()
	{
		global $APPLICATION;
		return CUtil::JSEscape($APPLICATION->GetTitle(false, true));
	}

	public function ShowPopupCSS()
	{
		if ($this->publicMode)
		{
			return '';
		}

		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$this->Init();

		$arCSS = array_merge(
			$this->GetModulesCSS($_REQUEST['from_module']),
			$APPLICATION->GetCSSArray()
		);

		$s = '<script type="text/javascript" bxrunfirst>'."\n";
		for ($i = 0, $cnt = count($arCSS); $i < $cnt; $i++)
		{
			$bExternalLink = (strncmp($arCSS[$i], 'http://', 7) == 0 || strncmp($arCSS[$i], 'https://', 8) == 0);
			if($bExternalLink || file_exists($_SERVER['DOCUMENT_ROOT'].$arCSS[$i]))
				$s .= 'top.BX.loadCSS(\''.CUtil::JSEscape($arCSS[$i]).'\');'."\n";
		}
		$s .= '</script>';
		return $s;
	}

	public function ShowCSS()
	{
		if ($this->publicMode)
		{
			return '';
		}

		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$this->Init();

		$arCSS = array_merge(array(
				ADMIN_THEMES_PATH.'/'.ADMIN_THEME_ID.'/compatible.css',
				//ADMIN_THEMES_PATH.'/'.ADMIN_THEME_ID.'/adminstyles.css',
				'/bitrix/panel/main/adminstyles_fixed.css',
				'/bitrix/panel/main/admin.css',
			),
			$this->GetModulesCSS(),
			$APPLICATION->GetCSSArray()
		);

		$s = '';
		foreach($arCSS as $css)
		{
			$bExternalLink = (strncmp($css, 'http://', 7) == 0 || strncmp($css, 'https://', 8) == 0);
			if($bExternalLink || file_exists($_SERVER['DOCUMENT_ROOT'].$css))
				$s .= '<link rel="stylesheet" type="text/css" href="'.($bExternalLink? $css : CUtil::GetAdditionalFileURL($css, true)).'">'."\n";
		}
		return $s;
	}

	public function GetModulesCSS($module_id='')
	{
		global $CACHE_MANAGER;
		$rel_theme_path = ADMIN_THEMES_PATH."/".ADMIN_THEME_ID."/";
		$abs_theme_path = $_SERVER["DOCUMENT_ROOT"].$rel_theme_path;

		if($module_id <> '' && $this->aModules[$module_id] <> '')
		{
			if(file_exists($abs_theme_path.$module_id.".css"))
				return array($rel_theme_path.$module_id.'.css');
		}

		if($CACHE_MANAGER->Read(36000000, ADMIN_THEME_ID, "modules_css"))
			$time_cached = $CACHE_MANAGER->Get(ADMIN_THEME_ID);
		else
			$time_cached = '';

		//check modification time
		$time_fact = '';
		foreach($this->aModules as $module)
		{
			$fname = $abs_theme_path.$module.".css";
			if(file_exists($fname))
				$time_fact .= filemtime($fname);
		}

		$css_file = $abs_theme_path."modules.css";

		if($time_fact !== $time_cached)
		{
			//parse css files to create summary modules css
			$sCss = '';
			foreach($this->aModules as $module)
			{
				$fname = $abs_theme_path.$module.".css";
				if(file_exists($fname))
					$sCss .= file_get_contents($fname)."\n";
			}

			//create summary modules css
			file_put_contents($css_file, $sCss);

			if($time_cached !== '')
			{
				$CACHE_MANAGER->Clean(ADMIN_THEME_ID, "modules_css");
				$CACHE_MANAGER->Read(36000000, ADMIN_THEME_ID, "modules_css");
			}

			$CACHE_MANAGER->Set(ADMIN_THEME_ID, $time_fact);
		}

		if(file_exists($css_file))
			return array($rel_theme_path.'modules.css');
		else
			return array();
	}

	public function ShowScript()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$APPLICATION->AddHeadScript('/bitrix/js/main/utils.js');
		$APPLICATION->AddHeadScript('/bitrix/js/main/hot_keys.js');

		$APPLICATION->SetAdditionalCSS('/bitrix/panel/main/hot_keys.css');

		if ($this->publicMode)
		{
			return '';
		}

		//PHP-depended variables
		$aUserOpt = CUserOptions::GetOption("global", "settings");
		$s = "
<script type=\"text/javascript\">
var phpVars = {
	'ADMIN_THEME_ID': '".CUtil::JSEscape(ADMIN_THEME_ID)."',
	'LANGUAGE_ID': '".CUtil::JSEscape(LANGUAGE_ID)."',
	'FORMAT_DATE': '".CUtil::JSEscape(FORMAT_DATE)."',
	'FORMAT_DATETIME': '".CUtil::JSEscape(FORMAT_DATETIME)."',
	'opt_context_ctrl': ".($aUserOpt["context_ctrl"] == "Y"? "true":"false").",
	'cookiePrefix': '".CUtil::JSEscape(COption::GetOptionString("main", "cookie_name", "BITRIX_SM"))."',
	'titlePrefix': '".CUtil::JSEscape(COption::GetOptionString("main", "site_name", $_SERVER["SERVER_NAME"]))." - ',
	'bitrix_sessid': '".bitrix_sessid()."',
	'messHideMenu': '".CUtil::JSEscape(GetMessage("admin_lib_hide_menu"))."',
	'messShowMenu': '".CUtil::JSEscape(GetMessage("admin_lib_show_menu"))."',
	'messHideButtons': '".CUtil::JSEscape(GetMessage("admin_lib_less_buttons"))."',
	'messShowButtons': '".CUtil::JSEscape(GetMessage("admin_lib_more_buttons"))."',
	'messFilterInactive': '".CUtil::JSEscape(GetMessage("admin_lib_filter_clear"))."',
	'messFilterActive': '".CUtil::JSEscape(GetMessage("admin_lib_filter_set"))."',
	'messFilterLess': '".CUtil::JSEscape(GetMessage("admin_lib_filter_less"))."',
	'messLoading': '".CUtil::JSEscape(GetMessage("admin_lib_loading"))."',
	'messMenuLoading': '".CUtil::JSEscape(GetMessage("admin_lib_menu_loading"))."',
	'messMenuLoadingTitle': '".CUtil::JSEscape(GetMessage("admin_lib_loading_title"))."',
	'messNoData': '".CUtil::JSEscape(GetMessage("admin_lib_no_data"))."',
	'messExpandTabs': '".CUtil::JSEscape(GetMessage("admin_lib_expand_tabs"))."',
	'messCollapseTabs': '".CUtil::JSEscape(GetMessage("admin_lib_collapse_tabs"))."',
	'messPanelFixOn': '".CUtil::JSEscape(GetMessage("admin_lib_panel_fix_on"))."',
	'messPanelFixOff': '".CUtil::JSEscape(GetMessage("admin_lib_panel_fix_off"))."',
	'messPanelCollapse': '".CUtil::JSEscape(GetMessage("admin_lib_panel_hide"))."',
	'messPanelExpand': '".CUtil::JSEscape(GetMessage("admin_lib_panel_show"))."'
};
</script>
";

		CJSCore::Init(array('admin_sidepanel'));

		$APPLICATION->AddHeadScript('/bitrix/js/main/admin_tools.js');
		$APPLICATION->AddHeadScript('/bitrix/js/main/popup_menu.js');
		$APPLICATION->AddHeadScript('/bitrix/js/main/admin_search.js');
		$APPLICATION->AddHeadScript('/bitrix/js/main/admin_sidepanel.js');

		return $s;
	}

	public function ShowSectionIndex($menu_id, $module_id=false)
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		echo '<div id="index_page_result_div">';

		$sTableID = "module_index_table";
		$page = $APPLICATION->GetCurPage();
		$param = DeleteParam(array("show_mode", "mode"));
		echo '
			<script>
			var '.$sTableID.' = new JCAdminList("'.$sTableID.'");
			jsUtils.addEvent(window, "unload", function(){'.$sTableID.'.Destroy(true);});

			function LoadIndex(mode)
			{
				'.$sTableID.'.Destroy(false);
				jsUtils.LoadPageToDiv("'.$page.'?show_mode="+mode+"&mode=list'.($param<>""? "&".$param:"").'", "index_page_result_div");
			}
			</script>
			';

		if($module_id === false)
			$this->Init();

		/** @global CAdminMenu() $adminMenu */
		global $adminMenu;

		$adminMenu->Init(($module_id !== false? array($module_id) : $this->aModules));
		$adminMenu->ShowSubmenu($menu_id, "table");

		echo '</div>';
	}

	function ShowSound()
	{
		/** @global CMain $APPLICATION */
		global $USER, $APPLICATION;

		$res = '';
		if($USER->IsAuthorized() && !isset($_COOKIE[COption::GetOptionString("main", "cookie_name", "BITRIX_SM").'_SOUND_LOGIN_PLAYED']))
		{
			$aUserOptGlobal = CUserOptions::GetOption("global", "settings");
			if($aUserOptGlobal["sound"] == 'Y')
			{
				if($aUserOptGlobal["sound_login"] == '')
					$aUserOptGlobal["sound_login"] = "/bitrix/sounds/main/bitrix_tune.mp3";

				ob_start();
				$APPLICATION->IncludeComponent("bitrix:player",	"audio",
					Array(
						"PATH" => htmlspecialcharsbx($aUserOptGlobal["sound_login"]),
						"WIDTH" => "1",
						"HEIGHT" => "1",
						"CONTROLBAR" => "none",
						"AUTOSTART" => "Y",
						"REPEAT" => "N",
						"VOLUME" => "90",
						"MUTE" => "N",
						"HIGH_QUALITY" => "Y",
						"BUFFER_LENGTH" => "2",
						"PROVIDER"=>"sound",
					),
					null, array("HIDE_ICONS"=>"Y")
				);
				$res = ob_get_contents();
				ob_end_clean();

				$res = '
<div style="position:absolute; top:-1000px; left:-1000px;">
'.$res.'
</div>
';
			}
		}
		return $res;
	}

	public function getSSOSwitcherButton()
	{
		global $CACHE_MANAGER, $USER;

		if($CACHE_MANAGER->Read(86400, "sso_portal_list_".$USER->GetID()))
		{
			$queryResult = $CACHE_MANAGER->Get("sso_portal_list_".$USER->GetID());
		}
		else
		{
			$queryResult = false;
			if(\Bitrix\Main\Loader::includeModule('socialservices'))
			{
				if(class_exists('CBitrix24NetTransport'))
				{
					$query = \CBitrix24NetTransport::init();
					if ($query)
					{
						$queryResult = $query->call('admin.profile.list', array());
					}

					$CACHE_MANAGER->Set("sso_portal_list_".$USER->GetID(), $queryResult);
				}
			}
		}

		if(is_array($queryResult))
		{
			$ssoMenu = array();

			if(isset($queryResult['error']))
			{
				if(
					$queryResult['error'] == 'insufficient_scope'
					&& \Bitrix\Main\Loader::includeModule('socialservices')
					&& class_exists("Bitrix\\Socialservices\\Network")
					&& method_exists("Bitrix\\Socialservices\\Network", "getAuthUrl")
				)
				{
					$n = new \Bitrix\Socialservices\Network();
					$ssoMenu[] =  array(
						"TEXT" => \Bitrix\Main\Localization\Loc::getMessage("admin_lib_sso_auth"),
						"TITLE" => \Bitrix\Main\Localization\Loc::getMessage("admin_lib_sso_auth_title"),
						"ONCLICK"=>"BX.util.popup('".CUtil::JSEscape($n->getAuthUrl("popup", array("admin")))."', 800, 600);",
					);
				}
			}
			elseif(isset($queryResult['result']))
			{
				$currentHost = \Bitrix\Main\Context::getCurrent()->getRequest()->getHttpHost();

				foreach($queryResult['result']['admin'] as $site)
				{
					if($site["TITLE"] != $currentHost)
					{
						$ssoMenu[] =  array(
							"TEXT" => $site["TITLE"],
							"TITLE"=> "Go to ". $site["TITLE"],
							"LINK"=>$site["URL"]."bitrix/admin/",
						);
					}
				}

				if(
					count($ssoMenu) > 0
					&& count($queryResult['result']["portal"]) > 0
				)
				{
					$ssoMenu[] = array("SEPARATOR" => true);
				}

				foreach($queryResult['result']['portal'] as $site)
				{
					$ssoMenu[] =  array(
						"TEXT" => $site["TITLE"],
						"TITLE"=> "Go to ". $site["TITLE"],
						"LINK"=>$site["URL"],
					);
				}
			}

			return $ssoMenu;
		}

		return false;
	}

	public function getSelfFolderUrl()
	{
		return (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");
	}
}

use Bitrix\Main\HttpResponse;
use Bitrix\Main\Application;
use Bitrix\Main\Web\Json;

class CAdminAjaxHelper
{
	/** @var  \Bitrix\Main\Context */
	protected $context;
	/** @var  \Bitrix\Main\HttpResponse */
	protected $httpResponse;
	/** @var  \Bitrix\Main\HttpRequest */
	protected $request;

	protected $skipResponse = false;

	public function __construct()
	{
		$this->context = Application::getInstance()->getContext();
		$this->request = $this->context->getRequest();
		$this->httpResponse = new HttpResponse($this->context);
	}

	/**
     * Sends JSON response with status "success".
	 * @throws \Bitrix\Main\ArgumentException
	 * @throws \Bitrix\Main\ArgumentNullException
	 * @throws \Bitrix\Main\ArgumentOutOfRangeException
	 */
	public function sendJsonSuccessResponse()
	{
		$this->sendJsonResponse(array("status" => "success"));
	}

	/**
     * Sends JSON response with status "error" and with errors.
	 * @param string $message Error message.
	 * @throws \Bitrix\Main\ArgumentException
	 * @throws \Bitrix\Main\ArgumentNullException
	 * @throws \Bitrix\Main\ArgumentOutOfRangeException
	 */
	public function sendJsonErrorResponse($message)
	{
		$this->sendJsonResponse(array("status" => "error", "message" => $message));
	}

	/**
	 * Sends JSON response.
	 * @param array $params Data structure.
	 * @throws \Bitrix\Main\ArgumentException
	 * @throws \Bitrix\Main\ArgumentNullException
	 * @throws \Bitrix\Main\ArgumentOutOfRangeException
	 */
	public function sendJsonResponse($params = array())
	{
		if ($this->isAjaxRequest() && !$this->skipResponse)
		{
			$this->httpResponse->addHeader("Content-Type", "application/json");
			$this->httpResponse->flush(Json::encode($params));
			$this->end();
		}
	}

	public function decodeUriComponent(Bitrix\Main\HttpRequest $request = null)
	{
		if ($this->isAjaxRequest())
		{
			if ($request)
			{
				$request->addFilter(new \Bitrix\Main\Web\PostDecodeFilter());
			}
			CUtil::decodeURIComponent($_GET);
			CUtil::decodeURIComponent($_POST);
			CUtil::decodeURIComponent($_REQUEST);
			$listKeys = array_keys($_REQUEST);
			foreach ($listKeys as $key)
				CUtil::decodeURIComponent($GLOBALS[$key]);
		}
	}

	/**
	 * Returns whether this is an AJAX (XMLHttpRequest) request.
	 * @return boolean
	 */
	public function isAjaxRequest()
	{
		return $this->request->isAjaxRequest();
	}

	protected function end()
	{
		define("ADMIN_AJAX_MODE", true);
		require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
		die();
	}
}

class CAdminSidePanelHelper extends CAdminAjaxHelper
{
	public function setSkipResponse($skip)
	{
		$this->skipResponse = $skip;
	}

	public function sendSuccessResponse($responseType = "", $dataToForm = array())
	{
		$post = $this->request->getPostList()->toArray();

		$listActions = array();
		switch ($responseType)
		{
			case "base":
				if ($post["save"] != "")
					$listActions[] = "destroy";
				if ($post["save_and_add"] != "")
					$listActions[] = "closeAndOpen";
				break;
			case "apply":
				if ($post["save"] != "")
					$listActions[] = "close";
				if ($post["apply"] != "")
					$listActions[] = "reload";
				break;
			case "close":
				$listActions[] = "close";
				break;
			case "destroy":
				$listActions[] = "destroy";
				break;
			default:
				$listActions[] = "close";
		}

		if (!empty($dataToForm["reloadUrl"]))
		{
			if ($this->isPublicSidePanel())
			{
				if (strpos("publicSidePanel", $dataToForm["reloadUrl"]) === false)
				{
					$dataToForm["reloadUrl"] = CHTTP::urlAddParams(
						$dataToForm["reloadUrl"], array("publicSidePanel" => "Y"));
				}
			}
		}

		$this->sendJsonResponse(
			array(
				"status" => "success",
				"listActions" => $listActions,

				"formParams" => $dataToForm
			)
		);
	}

	public function reloadPage($redirectUrl, $type)
	{
		if ($this->isSidePanelRequest())
		{
			$redirectUrl = CHTTP::urlAddParams($redirectUrl, array(
				"IFRAME" => "Y",
				"IFRAME_TYPE" => "SIDE_SLIDER",
				"sidePanelAction" => $type)
			);
			if ($this->isPublicSidePanel())
			{
				$redirectUrl = CHTTP::urlAddParams($redirectUrl, array("publicSidePanel" => "Y"));
			}
			LocalRedirect($redirectUrl);
		}
	}

	/**
	 * Returns whether this is an AJAX (XMLHttpRequest) request and SipePanel request.
	 * @return boolean
	 */
	public function isSidePanelRequest()
	{
		return ($_REQUEST["IFRAME"] == "Y") && ($_REQUEST["IFRAME_TYPE"] == "SIDE_SLIDER");
	}

	public function isSidePanel()
	{
		return (isset($_REQUEST["IFRAME"]) && $_REQUEST["IFRAME"] === "Y");
	}

	public function isPublicSidePanel()
	{
		return ($this->isSidePanel() && ($_REQUEST["publicSidePanel"] === "Y" || $_REQUEST["IFRAME_TYPE"] == "PUBLIC_FRAME"));
	}

	public function isSidePanelFrame()
	{
		return ($_REQUEST["IFRAME"] == "Y") && ($_REQUEST["IFRAME_TYPE"] == "SIDE_SLIDER");
	}

	public function isPublicFrame()
	{
		return ($_REQUEST["IFRAME"] == "Y") && ($_REQUEST["IFRAME_TYPE"] == "PUBLIC_FRAME");
	}

	public function setDefaultQueryParams($url)
	{
		if ($this->isSidePanel())
		{
			$frameType = "SIDE_SLIDER";
			if ($this->isPublicFrame())
			{
				$frameType = "PUBLIC_FRAME";
			}
			$params = array("IFRAME" => "Y", "IFRAME_TYPE" => $frameType);
			if ($this->isPublicSidePanel())
			{
				$params["publicSidePanel"] = "Y";
			}
			return \CHTTP::urlAddParams($url, $params);
		}
		else
		{
			return $url;
		}
	}

	public function editUrlToPublicPage($url)
	{
		if ($this->isPublicSidePanel() || (defined("PUBLIC_MODE") && PUBLIC_MODE == 1))
		{
			$url = str_replace(".php", "/", $url);
		}

		return $url;
	}

	public function localRedirect($url)
	{
		if ($this->isPublicFrame())
		{
			echo "<script>";
			echo "top.window.location.href = '".$url."';";
			echo "</script>";
			exit;
		}
	}
}

/* Left tree-view menu */
class CAdminMenu
{
	var $aGlobalMenu, $aActiveSections=array(), $aOpenedSections=array();
	var $bInit = false;

	public function __construct()
	{
	}

	function Init($modules)
	{
		/** @noinspection PhpUnusedLocalVariableInspection */
		global $APPLICATION, $USER, $DB, $MESS;

		if($this->bInit)
			return;
		$this->bInit = true;

		$aOptMenu = CUserOptions::GetOption("admin_menu", "pos", array());
		$this->AddOpenedSections($aOptMenu["sections"]);

		$aModuleMenu = array();
		if(is_array($modules))
		{
			foreach($modules as $module)
			{
				$module = _normalizePath($module);

				//trying to include file menu.php in the /admin/ folder of the current module
				$fname = getLocalPath("modules/".$module."/admin/menu.php");
				if($fname !== false)
				{
					$menu = CAdminMenu::_IncludeMenu($_SERVER["DOCUMENT_ROOT"].$fname);
					if(is_array($menu) && !empty($menu))
					{
						if(isset($menu["parent_menu"]) && $menu["parent_menu"] <> "")
						{
							//one section
							$aModuleMenu[] = $menu;
						}
						else
						{
							//multiple sections
							foreach($menu as $submenu)
							{
								if(is_array($submenu) && !empty($submenu))
								{
									$aModuleMenu[] = $submenu;
								}
							}
						}
					}
				}
			}
		}

		//additional user menu
		$aMenuLinks = array();
		if(file_exists($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/admin/.left.menu.php"))
			include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/admin/.left.menu.php");
		if(!empty($aMenuLinks))
		{
			$bWasSeparator = false;
			$menu = array();
			foreach($aMenuLinks as $module_menu)
			{
				if($module_menu[3]["SEPARATOR"] == "Y")
				{
					//first level
					if(!empty($menu))
						$aModuleMenu[] = $menu;

					$menu = array(
						"parent_menu" => "global_menu_services",
						"icon" => "default_menu_icon",
						"page_icon" => "default_page_icon",
						"items_id"=>$module_menu[3]["SECTION_ID"],
						"items"=>array(),
						"sort"=>$module_menu[3]["SORT"],
						"text" => $module_menu[0],
					);
					$bWasSeparator = true;
				}
				elseif($bWasSeparator && $module_menu[3]["SECTION_ID"] == "")
				{
					//section items
					$menu["items"][] = array(
						"text" => $module_menu[0],
						"title"=>$module_menu[3]["ALT"],
						"url" => $module_menu[1],
						"more_url"=>$module_menu[2],
					);
				}
				elseif($module_menu[3]["SECTION_ID"] == "" || $module_menu[3]["SECTION_ID"] == "statistic" || $module_menu[3]["SECTION_ID"] == "sale")
				{
					//item in root
					$aModuleMenu[] = array(
						"parent_menu" => ($module_menu[3]["SECTION_ID"] == "statistic"? "global_menu_statistics" : ($module_menu[3]["SECTION_ID"] == "sale"? "global_menu_store":"global_menu_services")),
						"icon" => "default_menu_icon",
						"page_icon" => "default_page_icon",
						"sort"=>$module_menu[3]["SORT"],
						"text" => $module_menu[0],
						"title"=>$module_menu[3]["ALT"],
						"url" => $module_menu[1],
						"more_url"=>$module_menu[2],
					);
				}
				else
				{
					//item in section
					foreach($aModuleMenu as $i=>$section)
					{
						if($section["section"] == $module_menu[3]["SECTION_ID"])
						{
							if(!is_array($aModuleMenu[$i]["items"]))
								$aModuleMenu[$i]["items"] = array();

							$aModuleMenu[$i]["items"][] = array(
								"text" => $module_menu[0],
								"title"=>$module_menu[3]["ALT"],
								"url" => $module_menu[1],
								"more_url"=>$module_menu[2],
							);
							break;
						}
					}
				}
			}
			if(!empty($menu))
				$aModuleMenu[] = $menu;
		}

		$this->aGlobalMenu = array(
			"global_menu_desktop" => array(
				"menu_id" => "desktop",
				"text" => GetMessage('admin_lib_desktop'),
				"title" => GetMessage('admin_lib_desktop_title'),
				"url" => "index.php?lang=".LANGUAGE_ID,
				"sort" => 50,
				"items_id" => "global_menu_desktop",
				"help_section" => "desktop",
				"items" => array()
			),
			"global_menu_content" => array(
				"menu_id" => "content",
				"text" => GetMessage("admin_lib_menu_content"),
				"title" => GetMessage("admin_lib_menu_content_title"),
				"sort" => 100,
				"items_id" => "global_menu_content",
				"help_section" => "content",
				"items" => array()
			),
			"global_menu_landing" => array(
				"menu_id" => "landing",
				"text" => GetMessage("admin_lib_menu_landing"),
				"sort" => 130,
				"items_id" => "global_menu_landing",
				"help_section" => "landing",
				"items" => array()
			),
			"global_menu_marketing" => array(
				"menu_id" => "marketing",
				"text" => GetMessage("admin_lib_menu_marketing"),
				"sort" => 150,
				"items_id" => "global_menu_marketing",
				"help_section" => "marketing",
				"items" => array()
			),
			"global_menu_store" => array(
				"menu_id" => "store",
				"text" => GetMessage("admin_lib_menu_store"),
				"title" => GetMessage("admin_lib_menu_store_title"),
				"sort" => 200,
				"items_id" => "global_menu_store",
				"help_section" => "store",
				"items" => array()
			),
			"global_menu_services" => array(
				"menu_id" => "services",
				"text" => GetMessage("admin_lib_menu_services"),
				"title" => GetMessage("admin_lib_menu_service_title"),
				"sort" => 300,
				"items_id" => "global_menu_services",
				"help_section" => "service",
				"items" => array()
			),
			"global_menu_statistics" => array(
				"menu_id" => "analytics",
				"text" => GetMessage("admin_lib_menu_stat"),
				"title" => GetMessage("admin_lib_menu_stat_title"),
				"sort" => 400,
				"items_id" => "global_menu_statistics",
				"help_section" => "statistic",
				"items" => array()
			),
			"global_menu_marketplace" => array(
				"menu_id" => "marketPlace",
				"text" => GetMessage("admin_lib_menu_marketplace"),
				"title" => GetMessage("admin_lib_menu_marketplace_title"),
				"url" => "update_system_market.php?lang=".LANGUAGE_ID,
				"sort" => 450,
				"items_id" => "global_menu_marketplace",
				"help_section" => "marketplace",
				"items" => array()
			),
			"global_menu_settings" => array(
				"menu_id" => "settings",
				"text" => GetMessage("admin_lib_menu_settings"),
				"title" => GetMessage("admin_lib_menu_settings_title"),
				"sort" => 500,
				"items_id" => "global_menu_settings",
				"help_section" => "settings",
				"items" => array()
			),
		);

		//User defined global sections
		$bSort = false;
		foreach(GetModuleEvents("main", "OnBuildGlobalMenu", true) as $arEvent)
		{
			$bSort = true;
			$arRes = ExecuteModuleEventEx($arEvent, array(&$this->aGlobalMenu, &$aModuleMenu));
			if(is_array($arRes))
				$this->aGlobalMenu = array_merge($this->aGlobalMenu, $arRes);
		}
		if($bSort)
			uasort($this->aGlobalMenu, array($this, '_sort'));

		foreach($aModuleMenu as $menu)
			$this->aGlobalMenu[$menu["parent_menu"]]["items"][] = $menu;

		$sort_func = array($this, '_sort');
		foreach($this->aGlobalMenu as $key => $menu)
		{
			if(empty($menu["items"]) && $key != "global_menu_desktop")
			{
				unset($this->aGlobalMenu[$key]);
			}
			elseif(is_array($this->aGlobalMenu[$key]["items"]))
			{
				usort($this->aGlobalMenu[$key]["items"], $sort_func);
			}
		}

		foreach($this->aGlobalMenu as $key=>$menu)
			if($this->_SetActiveItems($this->aGlobalMenu[$key]))
				break;
	}

	function _sort($a, $b)
	{
		if($a["sort"] == $b["sort"])
			return 0;
		return ($a["sort"] < $b["sort"]? -1 : 1);
	}

	function _IncludeMenu($fname)
	{
		/** @noinspection PhpUnusedLocalVariableInspection */
		global $APPLICATION, $USER, $DB, $MESS;

		$aModuleMenuLinks = array();
		$menu =  include($fname);

		if(is_array($menu) && !empty($menu))
			return $menu;

		if(!empty($aModuleMenuLinks))
		{
			$menu = array();
			$n = 0;
			foreach($aModuleMenuLinks as $module_menu)
			{
				if($n == 0)
				{
					//first level
					$menu = array(
						"parent_menu" => "global_menu_services",
						"icon" => "default_menu_icon",
						"page_icon" => "default_page_icon",
						"items_id"=>"sect_".md5($fname),
						"items"=>array(),
						"sort"=>$module_menu[3]["SORT"],
						"text" => $module_menu[0],
						"url" => $module_menu[1],
					);
				}
				else
				{
					//section items
					$menu["items"][] = array(
						"text" => $module_menu[0],
						"title"=>$module_menu[3]["ALT"],
						"url" => $module_menu[1],
						"more_url"=>$module_menu[2],
					);
				}
				$n++;
			}
			return $menu;
		}
		return false;
	}

	function _SetActiveItems(&$aMenu, $aSections=array())
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$bSubmenu = (isset($aMenu["items"]) && is_array($aMenu["items"]) && !empty($aMenu["items"]));
		if($bSubmenu)
			$aSections[$aMenu["items_id"]] = array(
				"menu_id" => $aMenu["menu_id"],
				"items_id"=>$aMenu["items_id"],
				"page_icon"=>isset($aMenu["page_icon"])? $aMenu["page_icon"]: null,
				"text"=>$aMenu["text"],
				"url"=>$aMenu["url"],
				"skip_chain"=>isset($aMenu["skip_chain"])? $aMenu["skip_chain"]: null,
				"help_section"=>isset($aMenu["help_section"])? $aMenu["help_section"]: null,
			);

		$bSelected = false;
		$bMoreUrl = (isset($aMenu["more_url"]) && is_array($aMenu["more_url"]) && !empty($aMenu["more_url"]));
		if($aMenu["url"] <> "" || $bMoreUrl)
		{
			$cur_page = $APPLICATION->GetCurPage();

			$all_links = array();
			if($aMenu["url"] <> "")
				$all_links[] = $aMenu["url"];
			if($bMoreUrl)
				$all_links = array_merge($all_links, $aMenu["more_url"]);

			$n = count($all_links);
			for($j = 0; $j < $n; $j++)
			{
				//"/admin/"
				//"/admin/index.php"
				//"/admin/index.php?module=mail"
				if(empty($all_links[$j]))
					continue;

				if(strpos($all_links[$j], "/bitrix/admin/") !== 0)
					$tested_link = "/bitrix/admin/".$all_links[$j];
				else
					$tested_link = $all_links[$j];

				if(strlen($tested_link) > 0 && strpos($cur_page, $tested_link) === 0)
				{
					$bSelected = true;
					break;
				}

				if(($pos = strpos($tested_link, "?"))!==false)
				{
					if(substr($tested_link, 0, $pos)==$cur_page)
					{
						$right = substr($tested_link, $pos+1);
						$params = explode("&", $right);
						$bOK = true;

						foreach ($params as $paramKeyAndValue)
						{
							$eqpos = strpos($paramKeyAndValue, "=");
							$varvalue = "";
							if($eqpos === false)
							{
								$varname = $paramKeyAndValue;
							}
							elseif($eqpos == 0)
							{
								continue;
							}
							else
							{
								$varname = substr($paramKeyAndValue, 0, $eqpos);
								$varvalue = urldecode(substr($paramKeyAndValue, $eqpos+1));
							}

							$globvarvalue = isset($_REQUEST[$varname]) ? $_REQUEST[$varname] : "";
							if($globvarvalue != $varvalue)
							{
								$bOK = false;
								break;
							}
						} //foreach ($params as $paramKeyAndValue)

						if($bOK)
						{
							$bSelected = true;
							break;
						}
					}//if(substr($tested_link, 0, $pos)==$cur_page)
				} //if(($pos = strpos($tested_link, "?"))!==false)
			} //for($j = 0; $j < $n; $j++)
		}

		$bSelectedInside = false;
		if($bSubmenu)
		{
			foreach($aMenu["items"] as $key=>$submenu)
				if($this->_SetActiveItems($aMenu["items"][$key], $aSections))
				{
					$bSelectedInside = true;
					break;
				}
		}

		if($bSelected && !$bSelectedInside)
		{
			if(!$bSubmenu)
			{
				$aSections["_active"] = array(
					"menu_id"=>$aMenu["menu_id"],
					"page_icon"=>$aMenu["page_icon"],
					"text"=>$aMenu["text"],
					"url"=>$aMenu["url"],
					"skip_chain"=>$aMenu["skip_chain"],
					"help_section"=>$aMenu["help_section"],
				);
			}
			$aMenu["_active"] = true;
			$this->aActiveSections = $aSections;
		}

		return $bSelected || $bSelectedInside;
	}

	private function _get_menu_item_width($level)
	{
		static $START_MAGIC_NUMBER = 30, $STEP_MAGIC_NUMBER = 21;
		return $START_MAGIC_NUMBER + $level*$STEP_MAGIC_NUMBER;
	}

	private function _get_menu_item_padding($level)
	{
		static $ADDED_MAGIC_NUMBER = 8;
		return $this->_get_menu_item_width($level) + $ADDED_MAGIC_NUMBER;
	}

	function Show($aMenu, $level=0)
	{
		$scripts = '';

		$bSubmenu = (isset($aMenu["items"]) && is_array($aMenu["items"]) && !empty($aMenu["items"])) || isset($aMenu["dynamic"]) && $aMenu["dynamic"] == true;
		$bSectionActive = isset($aMenu["items_id"]) && (in_array($aMenu["items_id"], array_keys($this->aActiveSections)) || $this->IsSectionActive($aMenu["items_id"]));

		$icon = isset($aMenu["icon"]) && $aMenu["icon"] <> ""
			? '<span class="adm-submenu-item-link-icon '.$aMenu["icon"].'"></span>'
//			: ($level < 1 ? '<span class="adm-submenu-item-link-icon" id="default_menu_icon"></span>' : '');
			: '';
		$id = 'menu_item_'.RandString(10);
		?><div class="adm-sub-submenu-block<?=$level > 0 ? ' adm-submenu-level-'.($level+1) : ''?><?=$bSectionActive && isset($aMenu["items"]) && is_array($aMenu["items"]) && count($aMenu['items']) > 0 ? ' adm-sub-submenu-open' : ''?><?=$aMenu["_active"] ? ' adm-submenu-item-active' : ''?>"><?
		?><div class="adm-submenu-item-name<?=!$bSubmenu ? ' adm-submenu-no-children' : ''?>" id="<?=$id?>" data-type="submenu-item"<?=isset($aMenu['fav_id']) ? ' data-fav-id="'.intval($aMenu['fav_id']).'"' : ''?>><?
		$onclick = '';
		if ($bSubmenu)
		{
			if(isset($aMenu["dynamic"]) && $aMenu["dynamic"] == true && (!$aMenu["items"] || count($aMenu["items"]) <= 0))
			{
				$onclick = "BX.adminMenu.toggleDynSection(".$this->_get_menu_item_width($level).", this.parentNode.parentNode, '".htmlspecialcharsbx(CUtil::JSEscape($aMenu["module_id"]))."', '".urlencode(htmlspecialcharsbx(CUtil::JSEscape($aMenu["items_id"])))."', '".($level+1)."')";
			}
			elseif(!$aMenu["dynamic"] || !$bSectionActive || $aMenu['dynamic'] && $bSectionActive && isset($aMenu["items"]) && count($aMenu["items"]) > 0)
			{
				$onclick = "BX.adminMenu.toggleSection(this.parentNode.parentNode, '".htmlspecialcharsbx(CUtil::JSEscape($aMenu["items_id"]))."', '".($level+1)."')";
			} //endif;
		}

		?><span class="adm-submenu-item-arrow"<?=$level > 0 ? ' style="width:'.$this->_get_menu_item_width($level).'px;"' : ''?><?=$onclick ? ' onclick="'.$onclick.'"' : ''?>><span class="adm-submenu-item-arrow-icon"></span></span><?

		$menuText = htmlspecialcharsbx(htmlspecialcharsback($aMenu["text"]));
		if(isset($aMenu["url"]) && $aMenu["url"] <> ""):
			$menuUrl = htmlspecialcharsbx($aMenu["url"], ENT_COMPAT, false);
			?><a class="adm-submenu-item-name-link<?=(isset($aMenu["readonly"]) && $aMenu["readonly"] == true? ' menutext-readonly':'')?>"<?=$level > 0 ? ' style="padding-left:'.$this->_get_menu_item_padding($level).'px;"' : ''?> href="<?=$menuUrl?>"><?=$icon?><span class="adm-submenu-item-name-link-text"><?=$menuText?></span></a><?
		elseif ($bSubmenu):
			if(isset($aMenu["dynamic"]) && $aMenu["dynamic"] == true && !$bSectionActive && (!$aMenu["items"] || count($aMenu["items"]) <= 0)):
				?><a class="adm-submenu-item-name-link<?=(isset($aMenu["readonly"]) && $aMenu["readonly"] == true? ' menutext-readonly':'')?>"<?=$level > 0 ? ' style="padding-left:'.$this->_get_menu_item_padding($level).'px;"' : ''?> href="javascript:void(0)" onclick="BX.adminMenu.toggleDynSection(<?=$this->_get_menu_item_width($level)?>, this.parentNode.parentNode, '<?=htmlspecialcharsbx(CUtil::JSEscape($aMenu["module_id"]))?>', '<?=htmlspecialcharsbx(CUtil::JSEscape($aMenu["items_id"]))?>', '<?=$level+1?>')"><?=$icon?><span class="adm-submenu-item-name-link-text"><?=$menuText?></span></a><?
			elseif(!$aMenu["dynamic"] || !$bSectionActive || $aMenu['dynamic'] && $bSectionActive && isset($aMenu["items"]) && count($aMenu["items"]) > 0):
				?><a class="adm-submenu-item-name-link<?=(isset($aMenu["readonly"]) && $aMenu["readonly"] == true? ' menutext-readonly':'')?>"<?=$level > 0 ? ' style="padding-left:'.$this->_get_menu_item_padding($level).'px;"' : ''?> href="javascript:void(0)" onclick="BX.adminMenu.toggleSection(this.parentNode.parentNode, '<?=htmlspecialcharsbx(CUtil::JSEscape($aMenu["items_id"]))?>', '<?=$level+1?>')"><?=$icon?><span class="adm-submenu-item-name-link-text"><?=$menuText?></span></a><?
			else:
				?><span class="adm-submenu-item-name-link<?=(isset($aMenu["readonly"]) && $aMenu["readonly"] == true? ' menutext-readonly':'')?>"<?=$level > 0 ? ' style="padding-left:'.$this->_get_menu_item_padding($level).'px"' : ''?>><?=$icon?><span class="adm-submenu-item-name-link-text"><?=$menuText?></span></span><?
			endif;
		else:
			?><span class="adm-submenu-item-name-link<?=(isset($aMenu["readonly"]) && $aMenu["readonly"] == true? ' menutext-readonly':'')?>"<?=$level > 0 ? ' style="padding-left:'.$this->_get_menu_item_padding($level).'px"' : ''?>><?=$icon?><span class="adm-submenu-item-name-link-text"><?=$menuText?></span></span><?
		endif;
		?></div><?

		if(($bSubmenu || (isset($aMenu["dynamic"]) && $aMenu["dynamic"] == true)) && is_array($aMenu["items"]))
		{
			echo  "<div class=\"adm-sub-submenu-block-children\">";
			foreach($aMenu["items"] as $submenu)
			{
				if($submenu)
				{
					$scripts .= $this->Show($submenu, $level+1);
				}
			}
			echo "</div>";
		}
		else
			echo  "<div class=\"adm-sub-submenu-block-children\"></div>";
?></div><?
		$url = str_replace("&amp;", "&", $aMenu['url']);

		if (isset($aMenu["fav_id"]))
		{
			$scripts .= "BX.adminMenu.registerItem('".$id."', {FAV_ID:'".CUtil::JSEscape($aMenu['fav_id'])."'});";
		}
		elseif (isset($aMenu["items_id"]) && $aMenu['url'])
		{
			$scripts .= "BX.adminMenu.registerItem('".$id."', {ID:'".CUtil::JSEscape($aMenu['items_id'])."', URL:'".CUtil::JSEscape($url)."', MODULE_ID:'".$aMenu['module_id']."'});";
		}
		elseif (isset($aMenu["items_id"]))
		{
			$scripts .= "BX.adminMenu.registerItem('".$id."', {ID:'".CUtil::JSEscape($aMenu['items_id'])."', MODULE_ID:'".$aMenu['module_id']."'});";
		}
		elseif ($aMenu['url'])
		{
			$scripts .= "BX.adminMenu.registerItem('".$id."', {URL:'".CUtil::JSEscape($url)."'});";
		}

		return $scripts;
	}

	function ShowIcons($aMenu)
	{
		foreach($aMenu["items"] as $submenu)
		{
			if(!$submenu)
				continue;
			echo
				'<div class="index-icon-block" align="center">'.
				'<a href="'.$submenu["url"].'" title="'.$submenu["title"].'"><div class="index-icon" id="'.($submenu["page_icon"]<>""? $submenu["page_icon"]:$aMenu["page_icon"]).'"></div>'.
				'<div class="index-label">'.$submenu["text"].'</div></a>'.
				'</div>';
		}
		echo '<br clear="all">';
	}

	function ShowList($aMenu)
	{
		foreach($aMenu["items"] as $submenu)
		{
			if(!$submenu)
				continue;
			echo '<div class="index-list" id="'.($submenu["icon"]<>""? $submenu["icon"]:$aMenu["icon"]).'"><a href="'.$submenu["url"].'" title="'.$submenu["title"].'">'.$submenu["text"].'</a></div>';
		}
	}

	function ShowTable($aMenu)
	{
		$sTableID = "module_index_table";
		// List init
		$lAdmin = new CAdminList($sTableID);

		// List headers
		$lAdmin->AddHeaders(array(
			array("id"=>"NAME", "content"=>GetMessage("admin_lib_index_name"), "default"=>true),
			array("id"=>"DESCRIPTION", "content"=>GetMessage("admin_lib_index_desc"), "default"=>true),
		));

		$n = 0;
		foreach($aMenu["items"] as $submenu)
		{
			// Populate list with data
			if(!$submenu)
				continue;
			$row = &$lAdmin->AddRow(0, null, $submenu["url"], GetMessage("admin_lib_index_go"));
			$row->AddField("NAME", '<a href="'.$submenu["url"].'" title="'.$submenu["title"].'">'.$submenu["text"].'</a>');
			$row->AddField("DESCRIPTION", $submenu["title"]);
			$n++;
		}

		$lAdmin->Display();

		echo '
<script>
'.$sTableID.'.InitTable();
</script>
';
	}

	function ShowSubmenu($menu_id, $mode="menu")
	{
		foreach($this->aGlobalMenu as $key=>$menu)
			if($this->_ShowSubmenu($this->aGlobalMenu[$key], $menu_id, $mode))
				break;
	}

	function _ShowSubmenu(&$aMenu, $menu_id, $mode, $level=0)
	{
		$bSubmenu = (is_array($aMenu["items"]) && count($aMenu["items"])>0);
		if($bSubmenu)
		{
			if($aMenu["items_id"] == $menu_id)
			{
				if($mode == "menu")
				{
					$menuScripts = "";
					foreach($aMenu["items"] as $submenu)
					{
						$menuScripts .= $this->Show($submenu, $level);
					}
					if ($menuScripts != "")
						echo '<script type="text/javascript">'.$menuScripts.'</script>';
				}
				elseif($mode == "icon")
					$this->ShowIcons($aMenu);
				elseif($mode == "list")
					$this->ShowList($aMenu);
				elseif($mode == "table")
					$this->ShowTable($aMenu);

				return true;
			}
			else
			{
				foreach($aMenu["items"] as $submenu)
					if($this->_ShowSubmenu($submenu, $menu_id, $mode, $level+1))
						return true;
			}
		}
		return false;
	}

	function ActiveSection()
	{
		if(!empty($this->aActiveSections))
			foreach($this->aActiveSections as $menu)
				return $menu;

		foreach($this->aGlobalMenu as $menu)
			return $menu;

		return null;
	}

	function ActiveIcon()
	{
		if(!empty($this->aActiveSections))
		{
			$aSections = array_keys($this->aActiveSections);
			for($i=count($aSections)-1; $i>=0; $i--)
				if($this->aActiveSections[$aSections[$i]]["page_icon"] <> "")
					return $this->aActiveSections[$aSections[$i]]["page_icon"];
		}
		return "default_page_icon";
	}

	function AddOpenedSections($sections)
	{
		$aSect = explode(",", $sections);
		foreach($aSect as $sect)
			if(trim($sect) <> "")
				$this->aOpenedSections[] = trim($sect);
	}

	function IsSectionActive($section)
	{
		return in_array($section, $this->aOpenedSections);
	}

	function GetOpenedSections()
	{
		return implode(",", $this->aOpenedSections);
	}
}

/* Popup menu */
class CAdminPopup
{
	var $name;
	var $id;
	var $items;
	var $params;

	public function __construct($name, $id, $items=false, $params=false)
	{
		//SEPARATOR, ID, ONCLICK, ICONCLASS, TEXT, DEFAULT=>true|false, DISABLED=>true|false
		$this->name = $name;
		$this->id = $id;
		$this->items = $items;
		$this->params = $params;
	}

	function Show($bReturnValue=false)
	{
		$s = '';
		if(!isset($_REQUEST["mode"]) || $_REQUEST["mode"] != "frame")
		{
			$s .=
'<script>
window.'.$this->name.' = new PopupMenu("'.$this->id.'"'.
	(is_array($this->params) && isset($this->params['zIndex'])? ', '.$this->params['zIndex']:'').
	(is_array($this->params) && isset($this->params['dxShadow'])? ', '.$this->params['dxShadow']:'').
');
';
			if(is_array($this->items))
			{
				$s .=
'window.'.$this->name.'.SetItems('.CAdminPopup::PhpToJavaScript($this->items).');
';
			}
			$s .=
'</script>
';
		}
		if($bReturnValue)
			return $s;
		else
			echo $s;
		return null;
	}

	public static function GetGlobalIconClass($old_icon)
	{
		switch($old_icon)
		{
			case 'edit':
				return 'adm-menu-edit';

			case 'view':
			case 'btn_fileman_view':
				return 'adm-menu-view';

			case 'copy':
				return 'adm-menu-copy';

			case 'move':
				return 'adm-menu-move';

			case 'rename':
				return 'adm-menu-rename';

			case 'delete':
				return 'adm-menu-delete';

			case 'btn_fileman_html':
				return 'adm-menu-edit-htm';

			case 'btn_fileman_php':
				return 'adm-menu-edit-php';

			case 'btn_fileman_text':
				return 'adm-menu-edit-txt';

			case 'btn_fileman_galka': // so it is
				return 'adm-menu-edit-wf';

			case 'btn_download':
				return 'adm-menu-download';

			case 'pack':
				return 'adm-menu-pack';

			case 'unpack':
				return 'adm-menu-unpack';

			case 'access':
				return 'adm-menu-access';

			case 'btn_fileman_prop':
				return 'adm-menu-folder-props';
		}

		return false;
	}

	public static function PhpToJavaScript($items)
	{
		$sMenuUrl = "[";
		if(is_array($items))
		{
			$i = 0;
			foreach($items as $action)
			{
				if($i > 0)
					$sMenuUrl .= ",\n";

				if(isset($action["SEPARATOR"]) && ($action["SEPARATOR"] === true || $action["SEPARATOR"] == "Y"))
					$sMenuUrl .= "{'SEPARATOR':true}";
				else
				{
					if($action["ONCLICK"] <> "")
						$action["ACTION"] = $action["ONCLICK"];

					if (isset($action["ICON"]) && $action["ICON"]<>""
						&& empty($action["GLOBAL_ICON"]))
					{
						$icon_global_class = CAdminPopup::GetGlobalIconClass($action["ICON"]);
						if ($icon_global_class)
						{
							$action["GLOBAL_ICON"] = $icon_global_class;
							unset($action["ICON"]);
						}
					}

					$sItem =
						(isset($action["LINK"]) && $action["LINK"]<>""? "'LINK':'".CUtil::JSEscape($action["LINK"])."',":"").
						(isset($action["DEFAULT"]) && $action["DEFAULT"] === true? "'DEFAULT':true,":"").
						(isset($action["CHECKED"]) && $action["CHECKED"] === true? "'CHECKED':true,":"").
						(isset($action["ICON"]) && $action["ICON"]<>""? "'ICONCLASS':'".CUtil::JSEscape($action["ICON"])."',":"").
						(isset($action["GLOBAL_ICON"]) && $action["GLOBAL_ICON"]<>""? "'GLOBAL_ICON':'".CUtil::JSEscape($action["GLOBAL_ICON"])."',":"").
						(isset($action["IMAGE"]) && $action["IMAGE"]<>""? "'IMAGE':'".CUtil::JSEscape($action["IMAGE"])."',":"").
						(isset($action["ID"]) && $action["ID"]<>""? "'ID':'".CUtil::JSEscape($action["ID"])."',":"").
						(isset($action["DISABLED"]) && $action["DISABLED"] == true? "'DISABLED':true,":"").
						(isset($action["AUTOHIDE"]) && $action["AUTOHIDE"] == false? "'AUTOHIDE':false,":"").
						(isset($action["DEFAULT"]) && $action["DEFAULT"] == true? "'DEFAULT':true,":"").
						($action["TEXT"]<>""? "'TEXT':'".CUtil::JSEscape($action["TEXT"])."',":"").
						($action["HTML"]<>""? "'HTML':'".CUtil::JSEscape($action["HTML"])."',":"").
						(isset($action["TITLE"]) && $action["TITLE"]<>""? "'TITLE':'".CUtil::JSEscape($action["TITLE"])."',":"").
						(isset($action["SHOW_TITLE"]) && $action["SHOW_TITLE"] == true ? "'SHOW_TITLE':true,":"").
						($action["ACTION"]<>""? "'ONCLICK':'".CUtil::JSEscape(str_replace("&amp;", "&", $action["ACTION"]))."',":"").
						(isset($action["ONMENUPOPUP"]) && $action["ONMENUPOPUP"]<>""? "'ONMENUPOPUP':'".CUtil::JSEscape($action["ONMENUPOPUP"])."',":"").
						(isset($action["MENU"]) && is_array($action["MENU"])? "'MENU':".CAdminPopup::PhpToJavaScript($action["MENU"]).",":"").
						(isset($action["MENU_URL"]) && $action["MENU_URL"]<>''? "'MENU_URL':'".CUtil::JSEscape($action["MENU_URL"])."',":"").
						(isset($action["MENU_PRELOAD"]) && $action["MENU_PRELOAD"] == true? "'MENU_PRELOAD':true,":"").
						(isset($action["CLOSE_ON_CLICK"]) && $action["CLOSE_ON_CLICK"] == false? "'CLOSE_ON_CLICK':false,":"");
					if($sItem <> "")
						$sItem = substr($sItem, 0, -1); //delete last comma
					$sMenuUrl .= "{".$sItem."}";
				}
				$i++;
			}
		}
		$sMenuUrl .= "]";
		return $sMenuUrl;
	}
}

class CAdminPopupEx extends CAdminPopup
{
	protected $element_id;

	/**
	 * @param string $element_id
	 * @param bool|array $items
	 * @param bool|array $params
	 */
	public function __construct($element_id, $items=false, $params=false)
	{
		//SEPARATOR, ID, ONCLICK|LINK, ICONCLASS, TEXT, DEFAULT=>true|false, MENU
		$this->element_id = $element_id;
		$this->items = $items;
		$this->params = $params;
	}

	public function Show($bReturnValue=false)
	{
		$s = '';
		if((!isset($_REQUEST["mode"]) || $_REQUEST["mode"] != "frame") && is_array($this->items))
		{
			$params = '';
			if (is_array($this->params))
				$params = ', '.CUtil::PhpToJsObject($params);

			$s .=
"<script type=\"text/javascript\">
BX.ready(function(){
	BX.bind(BX('".$this->element_id."'), 'click', function() {
		BX.adminShowMenu(this, ".CAdminPopup::PhpToJavaScript($this->items).$params.");
	});
});
</script>";
		}

		if($bReturnValue)
			return $s;
		else
			echo $s;
		return null;
	}
}

/* Context links menu for edit forms */
class CAdminContextMenu
{
	var $items;
	var $additional_items;
	var $bMenuAdded = false;
	var $bRightBarAdded = false;
	var $isSidePanel = false;
	var $isPublicMode = false;
	var $isPublicSidePanel = false;
	var $isPublicFrame = false;

	public function __construct($items, $additional_items = array())
	{
		global $adminSidePanelHelper;
		if (!is_object($adminSidePanelHelper))
		{
			require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");
			$adminSidePanelHelper = new CAdminSidePanelHelper();
		}

		$this->isSidePanel = $adminSidePanelHelper->isSidePanelFrame();
		$this->isPublicMode = (defined("PUBLIC_MODE") && PUBLIC_MODE == 1);
		$this->isPublicSidePanel = $adminSidePanelHelper->isPublicSidePanel();
		$this->isPublicFrame = $adminSidePanelHelper->isPublicFrame();

		$this->prepareItemLink($items);
		$this->prepareItemLink($additional_items);

		$this->items = $items;
		$this->additional_items = $additional_items;
	}

	function prepareItemLink(array &$listItems)
	{
		foreach ($listItems as &$item)
		{
			if (!empty($item["LINK"]) && !$item["PUBLIC"])
			{

				$selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");
				$reqValue = "/".str_replace("/", "\/", $selfFolderUrl)."/i";
				if (!preg_match($reqValue, $item["LINK"]) && !preg_match("/javascript:/", $item["LINK"]))
				{
					$item["LINK"] = $selfFolderUrl.$item["LINK"];
				}
			}

			switch ($item["ICON"])
			{
				case "btn_list":
					if ($this->isSidePanel)
					{
						if (isset($item["TYPE"]))
						{
							switch ($item["TYPE"])
							{
								case "default":
									global $adminSidePanelHelper;
									$item["LINK"] = $adminSidePanelHelper->setDefaultQueryParams($item["LINK"]);
									break;
							}
						}
						else
						{
							if (empty($item["ONCLICK"]))
							{
								$item["ONCLICK"] = "top.BX.onCustomEvent('SidePanel:close');";
							}
						}
					}
					else
					{
						if (!empty($item["LINK"]) && preg_match("/set_default/", $item["LINK"]))
							$item["LINK"] .= "&apply_filter=Y";
					}
					break;
				case "delete":
				case "btn_delete":
					if ($this->isSidePanel)
					{
						if (empty($item["ONCLICK"]))
						{
							$link = $item["ACTION"] ? $item["ACTION"] : $item["LINK"];
							if (preg_match("/javascript:/", $item["LINK"]) || !empty($item["ACTION"]))
							{
								if (preg_match("/window.location=(?P<postUrl>[^<]+(\"|\'))/", $link, $found) ||
									preg_match("/window.location.href=(?P<postUrl>[^<]+(\"|\'))/", $link, $found))
								{
									$confirmText = "";
									$postUrl = $found["postUrl"];
									if (preg_match("/confirm\((?P<text>[^<]+(\"|\'))\)/", $link, $found))
									{
										$confirmText = $found["text"];
									}

									if ($confirmText && $postUrl)
									{
										$item["ONCLICK"] = "if(confirm(".$confirmText.
										")) top.BX.onCustomEvent('AdminSidePanel:onSendRequest', [".$postUrl."]);";
									}

								}
								else
								{
									$item["ONCLICK"] = $item["LINK"];
								}
								unset($item["LINK"]);
								unset($item["ACTION"]);
							}
						}
					}
					break;
			}

			if (!empty($item["MENU"]))
			{
				$this->prepareItemLink($item["MENU"]);
			}
		}
	}

	/**
	 * @deprecated
	 * @param $items
	 * @param array $additional_items
	 */
	function CAdminContextMenu($items, $additional_items = array())
	{
		self::__construct($items, $additional_items);
	}

	function Show()
	{
		if (defined('BX_PUBLIC_MODE') && BX_PUBLIC_MODE == 1)
			return;

		foreach(GetModuleEvents("main", "OnAdminContextMenuShow", true) as $arEvent)
		{
			ExecuteModuleEventEx($arEvent, array(&$this->items, &$this->additional_items));
		}

		if(empty($this->items) && empty($this->additional_items))
		{
			return;
		}

		$hkInst = CHotKeys::getInstance();

		$bFirst = true;
		$bNeedSplitClosing = false;
		foreach($this->items as $item)
		{
			if(!empty($item["NEWBAR"]))
				$this->EndBar();

			if($bFirst || !empty($item["NEWBAR"]))
				$this->BeginBar();

			if(!empty($item["NEWBAR"]) || !empty($item['SEPARATOR']))
				continue;

			if ($item['ICON'] != 'btn_list' && !$bNeedSplitClosing)
			{
				$this->BeginRightBar();
				$bNeedSplitClosing = true;
			}

			$this->Button($item, $hkInst);

			$bFirst = false;
		}

		if (!empty($this->additional_items))
		{
			if($bFirst)
			{
				$this->BeginBar();
			}

			$this->Additional();
		}

		if ($bNeedSplitClosing)
			$this->EndRightBar();

		$this->EndBar();
	}

	function BeginBar()
	{
?>
<div class="adm-detail-toolbar"><span style="position:absolute;"></span>
<?
	}

	function EndBar()
	{
?>
</div>
<?
	}

	function BeginRightBar()
	{
		$id = 'context_right_'.RandString(8);
?>
<script type="text/javascript">BX.ready(function(){
var right_bar = BX('<?=$id?>');
BX.Fix(right_bar, {type: 'right', limit_node: BX.previousSibling(right_bar)});
})</script>
<div class="adm-detail-toolbar-right" id="<?=$id?>">
<?
	}

	function EndRightBar()
	{
?>
</div>
<?
	}

	function GetClassByID($icon_id)
	{
		switch ($icon_id)
		{
			case 'btn_new':
				return 'adm-btn-add';
			case 'btn_copy':
				return 'adm-btn-copy';
			case 'btn_delete':
				return 'adm-btn-delete';
			case 'btn_desktop_gadgets':
				return 'adm-btn-desktop-gadgets';
			case 'btn_desktop_settings':
				return 'adm-btn-desktop-settings';
			case 'btn_active':
				return 'adm-btn-active';
			case 'btn_green':
				return 'adm-btn-green';
		}

		return '';
	}

	function GetActiveClassByID($icon_id)
	{
		return 'adm-btn-active';
	}

	/**
	 * @param array $item
	 * @param CHotKeys $hkInst
	 */
	function Button($item, $hkInst)
	{
		// $item["ICON"]
		if(isset($item["HTML"]) && $item["HTML"] <> "")
		{
			echo '<span class="adm-list-table-top-wrapper">'.$item['HTML'].'</span>';
		}
		elseif(!empty($item["MENU"]))
		{

			$sMenuUrl = "BX.adminShowMenu(this, ".htmlspecialcharsbx(CAdminPopup::PhpToJavaScript($item["MENU"])).
				", {active_class: '".$this->GetActiveClassByID($item["ICON"])."', public_frame: '".($this->isPublicFrame ? 1 : 0)."'});";
			$sClassName = $this->GetClassByID($item["ICON"]);
?>
	<a href="javascript:void(0)" hidefocus="true" onclick="this.blur();<?=$sMenuUrl?> return false;" class="adm-btn<?=$sClassName != '' ? ' '.$sClassName : ''?> adm-btn-menu" title="<?=$item["TITLE"];?>"><?=$item["TEXT"]?></a>
<?
		}
		else
		{
			$link = htmlspecialcharsbx($item["LINK"], ENT_COMPAT, false);

			if ($item['ICON'] == 'btn_list'/* || $item['ICON'] == 'btn_up'*/):
?>
	<a <?if ($this->isPublicFrame):?>target="_top"<?endif;?> href="<?=($item["ONCLICK"] <> ''? 'javascript:void(0)' : $link)?>" <?=$item["LINK_PARAM"]?> class="adm-detail-toolbar-btn" title="<?=$item["TITLE"].$hkInst->GetTitle($item["ICON"])?>"<?=($item["ONCLICK"] <> ''? ' onclick="'.htmlspecialcharsbx($item["ONCLICK"]).'"':'')?><?=(!empty($item["ICON"])? ' id="'.$item["ICON"].'"':'')?>><span class="adm-detail-toolbar-btn-l"></span><span class="adm-detail-toolbar-btn-text"><?=$item["TEXT"]?></span><span class="adm-detail-toolbar-btn-r"></span></a>
<?
			else:
				$sClassName = $this->GetClassByID($item["ICON"]);
?>
	<a <?if ($this->isPublicFrame):?>target="_top"<?endif;?> href="<?=($item["ONCLICK"] <> ''? 'javascript:void(0)' : $link)?>" <?=$item["LINK_PARAM"]?> class="adm-btn<?=$sClassName != '' ? ' '.$sClassName : ''?>" title="<?=$item["TITLE"].$hkInst->GetTitle($item["ICON"])?>"<?=($item["ONCLICK"] <> ''? ' onclick="'.htmlspecialcharsbx($item["ONCLICK"]).'"' : '')?><?=(!empty($item["ICON"])? ' id="'.$item["ICON"].'"':'')?>><?=$item["TEXT"]?></a>

<?
			endif;

			$arExecs = $hkInst->GetCodeByClassName($item["ICON"]);
			echo $hkInst->PrintJSExecs($arExecs, "", true, true);
		}
	}

	function Additional()
	{
		$sMenuUrl = "BX.adminList.ShowMenu(this, ".htmlspecialcharsbx(CAdminPopup::PhpToJavaScript($this->additional_items)).");";
?>
	<div class="adm-small-button adm-table-setting" title="<?=htmlspecialcharsbx(GetMessage('admin_lib_context_sett_title'))?>" onclick="this.blur();<?=$sMenuUrl?> return false;" ></div>
<?
	}
}

/* Context links menu for lists */
class CAdminContextMenuList extends CAdminContextMenu
{
	function BeginBar()
	{
?>
<div class="adm-list-table-top">
<?
	}

	function GetClassByID($icon_id)
	{
		if (substr($icon_id, 0, 7) == 'btn_new')
			return 'adm-btn-save adm-btn-add';
		else
			return parent::GetClassByID($icon_id);
	}

	function GetActiveClassByID($icon_id)
	{
		if (substr($icon_id, 0, 7) == 'btn_new')
			return 'adm-btn-save-active';
		else
			return parent::GetActiveClassByID($icon_id);
	}

	function Button($item, $hkInst)
	{
		if (isset($item['ICON']) && $item['ICON'] == 'btn_list')
			$item['ICON'] = '';

		parent::Button($item, $hkInst);
	}

	function BeginRightBar() {}
	function EndRightBar() {}
}

/* Sorting in lists */
class CAdminSorting
{
	var $by_name;
	var $ord_name;
	var $table_id;
	var $by_initial;
	var $order_initial;

	protected $field;
	protected $order;

	/**
	 * @param string $table_id
	 * @param string|false $by_initial
	 * @param string|false $order_initial
	 * @param string $by_name
	 * @param string $ord_name
	 */
	public function __construct($table_id, $by_initial=false, $order_initial=false, $by_name="by", $ord_name="order")
	{
		$this->by_name = $by_name;
		$this->ord_name = $ord_name;
		$this->table_id = $table_id;
		$this->by_initial = $by_initial;
		$this->order_initial = $order_initial;

		$needUserByField = false;
		$needUserOrder = false;
		if(isset($GLOBALS[$this->by_name]))
		{
			$_SESSION["SESS_SORT_BY"][$this->table_id] = $GLOBALS[$this->by_name];
		}
		elseif(isset($_SESSION["SESS_SORT_BY"][$this->table_id]))
		{
			$GLOBALS[$this->by_name] = $_SESSION["SESS_SORT_BY"][$this->table_id];
		}
		else
		{
			$needUserByField = true;
		}

		if(isset($GLOBALS[$this->ord_name]))
		{
			$_SESSION["SESS_SORT_ORDER"][$this->table_id] = $GLOBALS[$this->ord_name];
		}
		elseif(isset($_SESSION["SESS_SORT_ORDER"][$this->table_id]))
		{
			$GLOBALS[$this->ord_name] = $_SESSION["SESS_SORT_ORDER"][$this->table_id];
		}
		else
		{
			$needUserOrder = true;
		}

		if ($needUserByField || $needUserOrder)
		{
			$userSorting = $this->getUserSorting();
			if ($needUserByField)
			{
				if (!empty($userSorting["by"]))
					$GLOBALS[$this->by_name] = $userSorting["by"];
				elseif ($this->by_initial !== false)
					$GLOBALS[$this->by_name] = $this->by_initial;
			}
			if ($needUserOrder)
			{
				if(!empty($userSorting["order"]))
					$GLOBALS[$this->ord_name] = $userSorting["order"];
				elseif($this->order_initial !== false)
					$GLOBALS[$this->ord_name] = $this->order_initial;
			}
		}

		$this->field = $GLOBALS[$this->by_name];
		$this->order = $GLOBALS[$this->ord_name];
	}

	/**
	 * @param string $text
	 * @param string $sort_by
	 * @param string|false $alt_title
	 * @param string $baseCssClass
	 * @return string
	 */
	public function Show($text, $sort_by, $alt_title = false, $baseCssClass = "")
	{
		$ord = "asc";
		$class = "";
		$title = GetMessage("admin_lib_sort_title")." ".($alt_title?$alt_title:$text);

		if(strtolower($this->field) == strtolower($sort_by))
		{
			if(strtolower($this->order) == "desc")
			{
				$class = "-down";
				$title .= " ".GetMessage("admin_lib_sort_down");
			}
			else
			{
				$class = "-up";
				$title .= " ".GetMessage("admin_lib_sort_up");
				$ord = "desc";
			}
		}

		$path = $_SERVER["REQUEST_URI"];
		$sep = "?";
		if($_SERVER["QUERY_STRING"] <> "")
		{
			$path = preg_replace("/([?&])".$this->by_name."=[^&]*[&]*/i", "\\1", $path);
			$path = preg_replace("/([?&])".$this->ord_name."=[^&]*[&]*/i", "\\1", $path);
			$path = preg_replace("/([?&])mode=[^&]*[&]*/i", "\\1", $path);
			$path = preg_replace("/([?&])table_id=[^&]*[&]*/i", "\\1", $path);
			$path = preg_replace("/([?&])action=[^&]*[&]*/i", "\\1", $path);
			$sep = "&";
		}
		if(($last = substr($path, -1, 1)) == "?" || $last == "&")
			$sep = "";

		$url = $path.$sep.$this->by_name."=".$sort_by."&".$this->ord_name."=".($class <> ""? $ord:"");

		return 'class="'.$baseCssClass.' adm-list-table-cell-sort'.$class.'" onclick="'.$this->table_id.'.Sort(\''.htmlspecialcharsbx(CUtil::addslashes($url)).'\', '.($class <> ""? "false" : "true").', arguments);" title="'.$title.'"';
	}

	/**
	 * @return string
	 */
	public function getField()
	{
		return $this->field;
	}

	/**
	 * @return string
	 */
	public function getOrder()
	{
		return $this->order;
	}

	/**
	 * @return array
	 */
	protected function getUserSorting()
	{
		$userSorting = CUserOptions::GetOption(
			"list",
			$this->table_id,
			array("by" => $this->by_initial, "order" => $this->order_initial)
		);
		return array(
			"by" => (!empty($userSorting["by"]) ? $userSorting["by"] : null),
			"order" => (!empty($userSorting["order"]) ? $userSorting["order"] : null)
		);
	}
}

/* Navigation */
/*
Important Notice:
	CIBlockResult has copy of the methods of this class
	because we need CIBlockResult::Fetch method to be called on iblock_element_admin.php page.
	So this page based on CIBlockResult not on CAdminResult!
*/
class CAdminResult extends CDBResult
{
	var $nInitialSize;
	var $table_id;

	/**
	* CAdminResult constructor.
	* @param mixed $res
	* @param string $table_id
	*/
	public function __construct($res, $table_id)
	{
		parent::__construct($res);
		$this->table_id = $table_id;
	}

	/**
	* @deprecated
 	* @param mixed $res
	* @param string $table_id
	*/
	public function CAdminResult($res, $table_id)
	{
		self::__construct($res, $table_id);
	}

	public function NavStart($nPageSize=20, $bShowAll=true, $iNumPage=false)
	{
		$nSize = self::GetNavSize($this->table_id, $nPageSize);

		if(!is_array($nPageSize))
			$nPageSize = array();

		$nPageSize["nPageSize"] = $nSize;
		if($_REQUEST["mode"] == "excel")
			$nPageSize["NavShowAll"] = true;

		$this->nInitialSize = $nPageSize["nPageSize"];

		parent::NavStart($nPageSize, $bShowAll, $iNumPage);
	}

	protected function parentNavStart($nPageSize, $bShowAll, $iNumPage)
	{
		parent::NavStart($nPageSize, $bShowAll, $iNumPage);
	}

	/**
	 * @param bool|string $table_id
	 * @param int|array $nPageSize
	 * @return int
	 */
	public function GetNavSize($table_id=false, $nPageSize=20)
	{
		/** @global CMain $APPLICATION */
		global $NavNum, $APPLICATION;

		if (!isset($NavNum))
			$NavNum = 0;

		$bSess = (CPageOption::GetOptionString("main", "nav_page_in_session", "Y")=="Y");
		if(is_array($nPageSize))
			$sNavID = $nPageSize["sNavID"];
		$unique = md5((isset($sNavID)? $sNavID : $APPLICATION->GetCurPage()));

		if(isset($_REQUEST["SIZEN_".($NavNum+1)]))
		{
			$nSize = (int)$_REQUEST["SIZEN_".($NavNum+1)];
			if($bSess)
				$_SESSION["NAV_PAGE_SIZE"][$unique] = $nSize;
		}
		elseif($bSess && isset($_SESSION["NAV_PAGE_SIZE"][$unique]))
		{
			$nSize = $_SESSION["NAV_PAGE_SIZE"][$unique];
		}
		else
		{
			$aOptions = array();
			if($table_id)
				$aOptions = CUserOptions::GetOption("list", $table_id);
			if(intval($aOptions["page_size"]) > 0)
				$nSize = intval($aOptions["page_size"]);
			else
				$nSize = (is_array($nPageSize)? $nPageSize["nPageSize"]:$nPageSize);
		}
		return $nSize;
	}

	public function GetNavPrint($title, $show_allways=true, $StyleText="", $template_path=false, $arDeleteParam=false)
	{
		if($template_path === false)
			$template_path = $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/interface/navigation.php";
		return parent::GetNavPrint($title, $show_allways, $StyleText, $template_path, array('action', 'sessid'));
	}
}

class CAdminMessage
{
	/** @var CAdminException */
	var $exception;
	var	$message;

	/**
	 * @param string|array $message
	 * @param CAdminException|bool $exception
	 */
	public function __construct($message, $exception=false)
	{
		//array("MESSAGE"=>"", "TYPE"=>("ERROR"|"OK"|"PROGRESS"), "DETAILS"=>"", "HTML"=>true)
		if(!is_array($message))
			$message = array("MESSAGE"=>$message, "TYPE"=>"ERROR");
		if(empty($message["DETAILS"]) && $exception !== false)
			$message["DETAILS"] = $exception->GetString();
		$this->message = $message;
		$this->exception = $exception;
	}

	/**
	* @deprecated
	 * @param string|array $message
	 * @param CAdminException|bool $exception
	*/
	public function CAdminMessage($message, $exception=false)
	{
		self::__construct($message, $exception);
	}

	function Show()
	{
		$publicMode = false;
		if (defined('BX_PUBLIC_MODE') && BX_PUBLIC_MODE == 1 && $this->message["TYPE"] != "PROGRESS" && (!isset($this->message['SKIP_PUBLIC_MODE']) || $this->message['SKIP_PUBLIC_MODE'] !== true))
		{
			$alertMessage = ($this->message['DETAILS'] <> ''? $this->message['DETAILS'] : $this->message['MESSAGE']);
			$alertMessage = htmlspecialcharsback($alertMessage); //we don't need html entities in an alert() box, see BX.CWindow.prototype.ShowError
			$alertMessage = str_replace(array('<br>', '<br />', '<BR>', '<BR />'), "\r\n", $alertMessage);

			ob_end_clean();
			echo "<script>
			var currentWindow = top.window;
			if (top.BX.SidePanel.Instance && top.BX.SidePanel.Instance.getTopSlider())
			{
				currentWindow = top.BX.SidePanel.Instance.getTopSlider().getWindow();
			}
			currentWindow.BX.WindowManager.Get().ShowError('".CUtil::JSEscape($alertMessage)."');</script>";
			die();
		}

		if (defined('PUBLIC_MODE') && PUBLIC_MODE == 1)
		{
			$publicMode = true;
			\Bitrix\Main\UI\Extension::load("ui.alerts");
		}

		if($this->message["MESSAGE"])
			$title = '<div class="adm-info-message-title">'.$this->_formatHTML($this->message["MESSAGE"]).'</div>';
		else
			$title = '';

		if($this->message["DETAILS"])
			$details = $this->_formatHTML($this->message["DETAILS"]);
		else
			$details = '';

		if($this->message["TYPE"] == "OK")
		{
			$baseClass = "adm-info-message-wrap adm-info-message-green";
			$messageClass = "adm-info-message";
			if ($publicMode)
			{
				$baseClass = "ui-alert ui-alert-success";
				$messageClass = "ui-btn-message";
			}

			$s = '
			<div class="'.$baseClass.'">
				<div class="'.$messageClass.'">
					'.$title.'
					'.$details.'
					<div class="adm-info-message-icon"></div>
				</div>
			</div>
			';
		}
		elseif($this->message["TYPE"] == "PROGRESS")
		{
			$baseClass = "adm-info-message-wrap adm-info-message-gray";
			$messageClass = "adm-info-message";
			if ($publicMode)
			{
				$baseClass = "ui-alert ui-alert-primary";
				$messageClass = "ui-btn-message";
			}

			if ($this->message['PROGRESS_ICON'])
				$title = '<div class="adm-info-message-icon-progress"></div>'.$title;

			$details = str_replace("#PROGRESS_BAR#", $this->_getProgressHtml(), $details);
			$s = '
			<div class="'.$baseClass.'">
				<div class="'.$messageClass.'">
					'.$title.'
					'.$details.'
					<div class="adm-info-message-buttons">'.$this->_getButtonsHtml().'</div>
				</div>
			</div>
			';
		}
		else
		{
			$baseClass = "adm-info-message-wrap adm-info-message-red";
			$messageClass = "adm-info-message";
			if ($publicMode)
			{
				$baseClass = "ui-alert ui-alert-danger";
				$messageClass = "ui-btn-message";
			}
			$s = '
			<div class="'.$baseClass.'">
				<div class="'.$messageClass.'">
					'.$title.'
					'.$details.'
					<div class="adm-info-message-icon"></div>
				</div>
			</div>
			';
		}

		return $s;
	}

	function _getProgressHtml()
	{
		$w = isset($this->message['PROGRESS_WIDTH']) ? intval($this->message['PROGRESS_WIDTH']) : 500;
		$p = 0;
		if ($this->message['PROGRESS_TOTAL'] > 0)
			$p = $this->message['PROGRESS_VALUE']/$this->message['PROGRESS_TOTAL'];

		if ($p < 0)
			$p = 0;
		elseif ($p > 1)
			$p = 1;

		$innerText = number_format(100*$p, 0) .'%';
		if ($this->message['PROGRESS_TEMPLATE'])
		{
			$innerText = str_replace(
				array('#PROGRESS_TOTAL#', '#PROGRESS_VALUE#', '#PROGRESS_PERCENT#'),
				array($this->message['PROGRESS_TOTAL'], $this->message['PROGRESS_VALUE'], $innerText),
				$this->message['PROGRESS_TEMPLATE']
			);
		}

		$s = '<div class="adm-progress-bar-outer" style="width: '.$w.'px;"><div class="adm-progress-bar-inner" style="width: '.intval($p*($w-4)).'px;"><div class="adm-progress-bar-inner-text" style="width: '.$w.'px;">'.$innerText.'</div></div>'.$innerText.'</div>';

		return $s;
	}

	function _getButtonsHtml()
	{
		$s = '';
		if(isset($this->message["BUTTONS"]) && is_array($this->message["BUTTONS"]))
		{
			foreach($this->message["BUTTONS"] as $button)
				$s .= '<input type="button" onclick="'.htmlspecialcharsbx($button["ONCLICK"]).'" value="'.htmlspecialcharsbx($button["VALUE"]).'" '.($button["ID"]? 'id="'.htmlspecialcharsbx($button["ID"]).'"': '').'>';
		}
		return $s;
	}

	function _formatHTML($html)
	{
		if($this->message["HTML"])
			return $html;
		else
			return _ShowHtmlspec($html);
	}

	function GetMessages()
	{
		if($this->exception && method_exists($this->exception, 'GetMessages'))
			return $this->exception->GetMessages();
		return false;
	}

	function ShowOldStyleError($message)
	{
		if(!empty($message))
		{
			$m = new CAdminMessage(array("MESSAGE"=>GetMessage("admin_lib_error"), "DETAILS"=>$message, "TYPE"=>"ERROR"));
			echo $m->Show();
		}
	}

	function ShowMessage($message)
	{
		if(!empty($message))
		{
			$m = new CAdminMessage($message);
			echo $m->Show();
		}
	}

	function ShowNote($message)
	{
		if(!empty($message))
			CAdminMessage::ShowMessage(array("MESSAGE"=>$message, "TYPE"=>"OK"));
	}
}

class CAdminChain
{
	var $items = array();
	var $id, $bVisible;

	public function __construct($id=false, $bVisible=true)
	{
		$this->id = $id;
		$this->bVisible = $bVisible;
	}

	function AddItem($item)
	{
		//array("TEXT"=>"", "LINK"=>"", "ONCLICK"=>"", "MENU"=>array(array("TEXT"=>"", "LINK"=>"", "CLASS"=>""), ...))
		$this->items[] = $item;
	}

	function Show()
	{
		if(empty($this->items))
			return null;

		$chainScripts = '';

?>
<div class="adm-navchain"<?=($this->id ? ' id="'.$this->id.'"':'').($this->bVisible == false? ' style="display:none;"' : '')?>>
<?
		$last_item = null;

		$cnt = count($this->items)-1;
		foreach($this->items as $n => $item)
		{
			$openerUrl = '/bitrix/admin/get_start_menu.php?skip_recent=Y&lang='.LANGUAGE_ID.($item['ID'] ? '&mode=chain&admin_mnu_menu_id='.urlencode($item['ID']) : '');

			$className = !empty($item['CLASS'])?' '.htmlspecialcharsbx($item['CLASS']):'';

			$text = htmlspecialcharsbx(htmlspecialcharsback($item["TEXT"]));
			if (!empty($item['LINK']))
			{
				$link = htmlspecialcharsbx($item["LINK"], ENT_COMPAT, false);
				echo '<a class="adm-navchain-item" href="'.$link.'"'.
					(!empty($item["ONCLICK"])? ' onclick="'.htmlspecialcharsbx($item["ONCLICK"]).'"':'').
					'><span class="adm-navchain-item-text'.$className.'">'.$text.'</span></a>';
			}
			elseif (!empty($item['ID']))
			{
				echo '<a href="javascript:void(0)" class="adm-navchain-item" id="bx_admin_chain_item_'.$item['ID'].'"><span class="adm-navchain-item-text'.$className.'">'.$text.'</span></a>';

				$chainScripts .= 'new BX.COpener('.CUtil::PhpToJsObject(array(
					'DIV' => 'bx_admin_chain_item_'.$item['ID'],
					'ACTIVE_CLASS' => 'adm-navchain-item-active',
					'MENU_URL' => $openerUrl
				)).');';

			}
			else
			{
				echo '<span class="adm-navchain-item adm-navchain-item-empty'.$className.'"><span class="adm-navchain-item-text">'.$text.'</span></span>';
			}

			if ($n < $cnt)
			{
				if($item['ID'] || ($n==0 && $this->id == 'main_navchain'))
				{
					echo '<span class="adm-navchain-item" id="bx_admin_chain_delimiter_'.$item['ID'].'"><span class="adm-navchain-delimiter"></span></span>';

					$chainScripts .= 'new BX.COpener('.CUtil::PhpToJsObject(array(
							'DIV' => 'bx_admin_chain_delimiter_'.$item['ID'],
							'ACTIVE_CLASS' => 'adm-navchain-item-active',
							'MENU_URL' => $openerUrl
						)).');';
				}
				else
				{
					echo '<span class="adm-navchain-delimiter"></span>';
				}

			}

			$last_item = $item;
		}
?>
</div>
<?
		if ($chainScripts != '')
		{
?>
<script type="text/javascript"><?=$chainScripts?></script>
<?
		}

		return $last_item;
	}
}

class CAdminMainChain extends CAdminChain
{
	var $bInit = false;

	public function __construct($id=false, $bVisible=true)
	{
		parent::__construct($id, $bVisible);
	}

	function Init()
	{
		/** @global CAdminPage $adminPage */
		global $adminPage;
		/** @global CAdminMenu $adminMenu */
		global $adminMenu;

		if($this->bInit)
			return;
		$this->bInit = true;
		$adminPage->Init();
		$adminMenu->Init($adminPage->aModules);

		parent::AddItem(array("TEXT"=> GetMessage("admin_lib_navchain_first"), "LINK"=>"/bitrix/admin/index.php?lang=".LANGUAGE_ID, "CLASS" => "adm-navchain-item-desktop"));

		foreach($adminMenu->aActiveSections as $sect)
		{
			if($sect["skip_chain"] !== true)
				parent::AddItem(array("TEXT"=>$sect["text"], "LINK"=>$sect["url"], "ID" => $sect['items_id']));
		}
	}

	function AddItem($item)
	{
		$this->Init();
		parent::AddItem($item);
	}
}

class CAdminTheme
{
	public static function GetList()
	{
		/** @noinspection PhpUnusedLocalVariableInspection */
		global $MESS;

		$aThemes = array();
		$dir = $_SERVER["DOCUMENT_ROOT"].ADMIN_THEMES_PATH;
		if(is_dir($dir) && ($dh = opendir($dir)))
		{
			while (($file = readdir($dh)) !== false)
			{
				if(is_dir($dir."/".$file) && $file!="." && $file!="..")
				{
					$path = ADMIN_THEMES_PATH."/".$file;

					$sLangFile = $_SERVER["DOCUMENT_ROOT"].$path."/lang/".LANGUAGE_ID."/.description.php";
					if(file_exists($sLangFile))
						include($sLangFile);
					else
					{
						$sLangFile = $_SERVER["DOCUMENT_ROOT"].$path."/lang/en/.description.php";
						if(file_exists($sLangFile))
							include($sLangFile);
					}

					$aTheme = array();
					$sDescFile = $_SERVER["DOCUMENT_ROOT"].$path."/.description.php";
					if(file_exists($sDescFile))
						$aTheme = include($sDescFile);
					$aTheme["ID"] = $file;
					if($aTheme["NAME"] == "")
						$aTheme["NAME"] = $file;

					$aThemes[] = $aTheme;
				}
			}
			closedir($dh);
		}
		usort($aThemes, create_function('$a, $b', 'return strcasecmp($a["ID"], $b["ID"]);'));
		return $aThemes;
	}

	public static function GetCurrentTheme()
	{
		$aUserOpt = CUserOptions::GetOption("global", "settings");
		if($aUserOpt["theme_id"] <> "")
		{
			$theme = preg_replace("/[^a-z0-9_.-]/i", "", $aUserOpt["theme_id"]);
			if($theme <> "")
			{
				return $theme;
			}
		}

		return ".default";
	}
}

class CAdminUtil
{
	public static function dumpVars($vars, $arExclusions = array())
	{
		$result = "";
		if (is_array($vars))
		{
			foreach ($vars as $varName => $varValue)
			{
				if (in_array($varName, $arExclusions))
					continue;

				$result .= self::dumpVar($varName, $varValue);
			}
		}

		return $result;
	}

	private static function dumpVar($varName, $varValue, $varStack = array())
	{
		$result = "";
		if (is_array($varValue))
		{
			foreach ($varValue as $key => $value)
			{
				$result .= self::dumpVar($key, $value, array_merge($varStack ,array($varName)));
			}
		}
		else
		{
			$htmlName = $varName;
			if (count($varStack) > 0)
			{
				$htmlName = $varStack[0];
				for ($i = 1, $intCount = count($varStack); $i < $intCount; $i++)
					$htmlName .= "[".$varStack[$i]."]";
				$htmlName .= "[".$varName."]";
			}

			return '<input type="hidden" name="'.htmlspecialcharsbx($htmlName).'" value="'.htmlspecialcharsbx($varValue).'">';
		}

		return $result;
	}
}

function ShowJSHint($text, $arParams=false)
{
	if ($text == '')
	{
		return '';
	}

	CJSCore::Init();

	$id = "h".mt_rand();

	$res = '
		<script type="text/javascript">BX.ready(function(){BX.hint_replace(BX("'.$id.'"), "'.CUtil::JSEscape($text).'");})</script>
		<span id="'.$id.'"></span>
	';

	if (isset($arParams['return']) && $arParams['return'])
	{
		return $res;
	}
	echo $res;
	return null;
}

prolog_jspopup_admin.php000064400000000723147732346240011525 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

Header('Content-Type: text/html; charset='.LANG_CHARSET);

ob_start();

if ($_REQUEST['suffix'] && !preg_match('/[^a-zA-Z0-9_]/is', $_REQUEST['suffix']))
{
	$obJSPopup = new CJSPopup($APPLICATION->GetTitle(false, true), array('SUFFIX' => $_REQUEST['suffix']));
}
else
{
	$obJSPopup = new CJSPopup($APPLICATION->GetTitle(false, true));
}

$obJSPopup->ShowTitlebar();
?>
<div id="bx_admin_form">
desktop.php000064400000001644147732346240006747 0ustar00<?
require_once(dirname(__FILE__)."/../include/prolog_admin_before.php");
IncludeModuleLangFile(__FILE__);

$adminPage->Init();
$adminMenu->Init($adminPage->aModules);

if(empty($adminMenu->aGlobalMenu))
	$APPLICATION->AuthForm(GetMessage("ACCESS_DENIED"));

$APPLICATION->SetAdditionalCSS("/bitrix/themes/".ADMIN_THEME_ID."/index.css");

$APPLICATION->SetTitle(GetMessage("admin_index_title"));

require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
?>
<?$APPLICATION->IncludeComponent(
	"bitrix:desktop",
	"admin",
	Array(
		"MODE" => "AI",
		"ID" => "admin_index",
		"MULTIPLE" => "Y",
		"CAN_EDIT" => "Y",
		"COLUMNS" => "2",
		"COLUMN_WIDTH_0" => "50%",
		"COLUMN_WIDTH_1" => "50%",
		"GADGETS" => Array("ALL"),
		"G_RSSREADER_SHOW_URL" => "Y",
	),
	false,
	array(
		"HIDE_ICONS" => "Y"
	)
	);?>
<?
require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin.php");
?>admin_notify.php000064400000000654147732346240007756 0ustar00<?
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

if($USER->IsAdmin() && isset($_POST["ID"]) && check_bitrix_sessid())
{
	CAdminNotify::Delete(intval($_POST["ID"]));
}
echo "OK";
require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
?>
favorite_menu.php000064400000000410147732346240010127 0ustar00<script type="text/javascript">
	BX.addCustomEvent(BX.adminMenu, 'onMenuChange', BX.delegate(BX.adminFav.onMenuChange, this));
</script>

<?
$favMenu = new CBXFavAdmMenu;
$favMenuText = GetMessage("MAIN_PR_ADMIN_FAV");
$favMenuItems = $favMenu->GenerateItems();
?>auth/wrapper_auth_result.php000064400000002006147732346240012327 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)
{
	die();
}

if (!is_array($arAuthResult))
{
	$arAuthResult = array("TYPE" => "ERROR", "MESSAGE" => $arAuthResult);
}

if($inc_file === "otp")
{
	$arAuthResult['CAPTCHA'] = CModule::IncludeModule("security")
		&& \Bitrix\Security\Mfa\Otp::isCaptchaRequired();
}
elseif($inc_file == 'forgot_password' || $inc_file == 'change_password')
{
	$arAuthResult['CAPTCHA'] = COption::GetOptionString("main", "captcha_restoring_password", "N") == "Y";
}
else
{
	$arAuthResult['CAPTCHA'] = $APPLICATION->NeedCAPTHAForLogin($last_login);
}

if ($arAuthResult['CAPTCHA'])
{
	$arAuthResult['CAPTCHA_CODE'] = $APPLICATION->CaptchaGetCode();
}

if ($bOnHit):
?>
<script type="text/javascript">
BX.ready(function(){BX.defer(BX.adminLogin.setAuthResult, BX.adminLogin)(<?=CUtil::PhpToJsObject($arAuthResult)?>);});
</script>
<?
else:
?>
<script type="text/javascript" bxrunfirst="true">
top.BX.adminLogin.setAuthResult(<?=CUtil::PhpToJsObject($arAuthResult)?>);
</script>
<?
endif;
?>auth/wrapper_popup.php000064400000011002147732346240011127 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

switch($_REQUEST['bxsender']):

/**********************************************************/
/************** core_window standard dialogs **************/
/**********************************************************/

	case 'core_window_cdialog':
	case 'core_window_cadmindialog':
?>
<script type="text/javascript" bxrunfirst="true">top.BX.WindowManager.Get().Authorize(<?=CUtil::PhpToJsObject($arAuthResult)?>)</script>
<?
	break;

/**********************************************************/
/************** Admin Wizard Dialog***********************/
/**********************************************************/

	case 'admin_wizard_dialog':
?>
<script type="text/javascript" bxrunfirst="true">
	(new top.BX.CAuthDialog({
		content_url: "/bitrix/admin/wizard_install.php",
		auth_result: <?=CUtil::PhpToJsObject($arAuthResult)?>,
		callback: function() {
			var frameWindow = top.WizardWindow.currentFrame.contentWindow;
			var reloadForm = frameWindow.document.forms["wizard_reload_form"];
			var submitButton = reloadForm.elements["reload_submit"];
			submitButton.click();
		}
	})).Show();
</script>

<form action="<?=$APPLICATION->GetCurPageParam(bitrix_sessid_get(), Array("sessid"))?>" method="post" name="wizard_reload_form">
	<input type="submit" name="reload_submit" value="Y" style="display: none;">
	<?=CAdminUtil::dumpVars($_POST, array("USER_LOGIN", "USER_PASSWORD", "sessid"));?>
</form>
<?
	break;

/**********************************************************/
/************** WYSIWYG editor requests *******************/
/**********************************************************/

	case 'fileman_html_editor':
?>
<script type="text/javascript" bxrunfirst="true">
	top.BX.onCustomEvent(top, 'OnHtmlEditorRequestAuthFailure', ['<?= CUtil::JSEscape($_REQUEST['bxeditor'])?>', <?=CUtil::PhpToJsObject($arAuthResult)?>]);
</script>
<?
	break;

/***************************************************************************************************/
/*************** core window auth dialog - we shold return auth form content ***********************/
/***************************************************************************************************/

	case 'core_window_cauthdialog':

		$store_password = COption::GetOptionString("main", "store_password", "Y");
		$bNeedCaptcha = $APPLICATION->NeedCAPTHAForLogin($last_login);

		ob_start();
?>
<form name="form_auth" method="post" action="" novalidate>
	<input type="hidden" name="AUTH_FORM" value="Y">
	<input type="hidden" name="TYPE" value="AUTH">

	<div class="bx-core-popup-auth-field">
		<div class="bx-core-popup-auth-field-caption"><?=GetMessage("AUTH_LOGIN")?></div>
		<div class="bx-core-popup-auth-field"><input type="text" name="USER_LOGIN" value="<?echo htmlspecialcharsbx($last_login)?>"></div>
	</div>
	<div class="bx-core-popup-auth-field">
		<div class="bx-core-popup-auth-field-caption"><?=GetMessage("AUTH_PASSWORD")?></div>
		<div class="bx-core-popup-auth-field"><input type="password" name="USER_PASSWORD"></div>
	</div>

<?
		if($store_password=="Y"):
?>
	<div class="bx-core-popup-auth-field">
		<input type="checkbox" class="adm-designed-checkbox" id="USER_REMEMBER" name="USER_REMEMBER" value="Y">
		<label for="USER_REMEMBER" class="adm-designed-checkbox-label"></label><label for="USER_REMEMBER">&nbsp;<?=GetMessage("AUTH_REMEMBER_ME")?></label>
	</div>
<?
		endif;

		$CAPTCHA_CODE = '';
		if($bNeedCaptcha):
			$CAPTCHA_CODE = $APPLICATION->CaptchaGetCode();
?>
	<input type="hidden" name="captcha_sid" value="<?=$CAPTCHA_CODE?>" />
	<div class="bx-core-popup-auth-field">
		<div class="bx-core-popup-auth-field-caption">
			<div><?=GetMessage("AUTH_CAPTCHA_PROMT")?></div>
			<img src="/bitrix/tools/captcha.php?captcha_sid=<?=$CAPTCHA_CODE?>" width="180" height="40" alt="CAPTCHA" />
		</div>
		<div class="bx-core-popup-auth-field"><input type="text" name="captcha_word"></div>
	</div>
<?
		endif; // $bNeedCaptcha
?>
</form>
<?
		$form = ob_get_contents();
		ob_end_clean();
?>
<script type="text/javascript">
var authWnd = top.BX.WindowManager.Get();
authWnd.SetTitle('<?=GetMessageJS('AUTH_TITLE')?>');
authWnd.SetContent('<?=CUtil::JSEscape($form)?>');
authWnd.SetError(<?=CUtil::PhpToJsObject($arAuthResult)?>);
authWnd.adjustSizeEx();
</script>
<?
		if(!CMain::IsHTTPS() && COption::GetOptionString('main', 'use_encrypted_auth', 'N') == 'Y')
		{
			$sec = new CRsaSecurity();
			if(($arKeys = $sec->LoadKeys()))
			{
				$sec->SetKeys($arKeys);
				$sec->AddToForm('form_auth', array('USER_PASSWORD'));
			}
		}

	break;
endswitch;
?>auth/otp.php000064400000006134147732346240007040 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

$store_password = (COption::GetOptionString('security', 'otp_allow_remember') === 'Y');
$bNeedCaptcha = (CModule::IncludeModule("security") && \Bitrix\Security\Mfa\Otp::isCaptchaRequired());
?>

<div class="login-main-popup-wrap login-popup-wrap<?=$bNeedCaptcha?" login-captcha-popup-wrap" : ""?>" id="otp">
	<input type="hidden" name="TYPE" value="OTP">
	<div class="login-popup">
		<div class="login-popup-title"><?=GetMessage('AUTH_TITLE')?></div>
		<div class="login-popup-title-description"><?=GetMessage("AUTH_PLEASE_AUTH")?></div>
		<div class="login-popup-field">
			<div class="login-popup-field-title"><?=GetMessage("AUTH_OTP_PASS")?></div>
			<div class="login-input-wrap">
				<input type="text" class="login-input" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="USER_OTP" value="" tabindex="1" autocomplete="off">
				<div class="login-inp-border"></div>
			</div>
			<input type="submit" value="" class="login-btn-green" name="Login" tabindex="5" onfocus="BX.addClass(this, 'login-btn-green-hover');" onblur="BX.removeClass(this, 'login-btn-green-hover')">
			<div class="login-loading">
				<img class="login-waiter" alt="" src="/bitrix/panel/main/images/login-waiter.gif">
			</div>
		</div>
<?
if($store_password):
?>
		<div class="login-popup-checbox-block">
			<input type="checkbox" class="adm-designed-checkbox" id="OTP_REMEMBER" name="OTP_REMEMBER" value="Y" tabindex="3" onfocus="BX.addClass(this.nextSibling, 'login-popup-checkbox-label-active')" onblur="BX.removeClass(this.nextSibling, 'login-popup-checkbox-label-active')"><label for="OTP_REMEMBER" class="adm-designed-checkbox-label"></label>
			<label for="OTP_REMEMBER" class="login-popup-checkbox-label"><?=GetMessage("AUTH_OTP_REMEMBER_ME")?></label>
		</div>
<?
endif;

$CAPTCHA_CODE = '';
if($bNeedCaptcha)
	$CAPTCHA_CODE = $APPLICATION->CaptchaGetCode();

?>
		<input type="hidden" name="captcha_sid" value="<?=$CAPTCHA_CODE?>" />
		<div class="login-popup-field login-captcha-field">
			<div class="login-popup-field-title"><?=GetMessage("AUTH_CAPTCHA_PROMT")?></div>
			<div class="login-input-wrap">
				<span class="login-captcha-wrap" id="captcha_image"><?if($bNeedCaptcha):?><img src="/bitrix/tools/captcha.php?captcha_sid=<?=$CAPTCHA_CODE?>" width="180" height="40" alt="CAPTCHA" /><?endif;?></span><input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="captcha_word" class="login-input" tabindex="4" autocomplete="off">
				<div class="login-inp-border"></div>
			</div>
		</div>
<?
if($not_show_links!="Y"):
?>
		<a class="login-popup-link login-popup-forget-pas" href="javascript:void(0)" onclick="BX.adminLogin.toggleAuthForm('authorize')"><?=GetMessage("AUTH_GOTO_AUTH_FORM_1")?></a>
<?
endif;
?>
	</div>
</div>
<script type="text/javascript">
BX.adminLogin.registerForm(new BX.authFormOtp('otp', {url: '<?echo CUtil::JSEscape($authUrl.(($s=DeleteParam(array("logout", "login"))) == ""? "":"?".$s));?>'}));
</script>
auth/wrapper.php000064400000013567147732346240007726 0ustar00<?
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2013 Bitrix
 */

/**
 * Bitrix vars
 * @global CMain $APPLICATION
 * @var string $inc_file From CMain::AuthForm()
 * @var array $arAuthResult From CMain::AuthForm()
 * @var string $sLinks From prolog_auth_admin.php
 * @var string $sCopyright From prolog_auth_admin.php
 */
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

IncludeModuleLangFile(__FILE__);

$arFormsList = array("authorize", "forgot_password", "change_password", "otp");
if (!in_array($inc_file, $arFormsList))
	$inc_file = $arFormsList[0];

function dump_post_var($vname, $vvalue, $var_stack=array())
{
	if(is_array($vvalue))
	{
		$str = "";
		foreach($vvalue as $key=>$value)
			$str .= ($str == "" ? '' : '&').dump_post_var($key, $value, array_merge($var_stack ,array($vname)));
		return $str;
	}
	else
	{
		if(count($var_stack)>0)
		{
			$var_name=$var_stack[0];
			$varStackCount = count($var_stack);
			for($i = 1; $i < $varStackCount; $i++)
				$var_name.="[".$var_stack[$i]."]";
			$var_name.="[".$vname."]";
		}
		else
			$var_name=$vname;

		return urlencode($var_name).'='.urlencode($vvalue);
	}
}

//last login from cookie
$last_login = ${COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_LOGIN"};
if (isset($_REQUEST['bxsender']))
{
	if ($_REQUEST['bxsender'] != 'core_autosave')
		require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/auth/wrapper_popup.php");

	return;
}

if(
	$arAuthResult
	&& defined('ADMIN_SECTION_LOAD_AUTH')
	&& ADMIN_SECTION_LOAD_AUTH || $_REQUEST['AUTH_FORM']
)
{
	$APPLICATION->RestartBuffer();
	include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/auth/wrapper_auth_result.php");
	die();
}

$post_data = '';
foreach($_POST as $vname=>$vvalue)
{
	if($vname=="USER_LOGIN" || $vname=="USER_PASSWORD" || $vname=="USER_OTP")
		continue;
	$post_data .= ($post_data == '' ? '' : '&').dump_post_var($vname, $vvalue);
}

if(!CMain::IsHTTPS() && COption::GetOptionString('main', 'use_encrypted_auth', 'N') == 'Y')
{
	$sec = new CRsaSecurity();
	if(($arKeys = $sec->LoadKeys()))
	{
		$sec->SetKeys($arKeys);
		$sec->AddToForm('form_auth', array('USER_PASSWORD', 'USER_CONFIRM_PASSWORD'));
		$bSecure = true;
	}
}

$sDocPath = $APPLICATION->GetCurPage();
$authUrl = (defined('BX_ADMIN_SECTION_404') && BX_ADMIN_SECTION_404 == 'Y') ? '/bitrix/admin/' : $sDocPath;
?>
<script type="text/javascript">
BX.message({
	'admin_authorize_error': '<?=GetMessageJS("admin_authorize_error")?>',
	'admin_forgot_password_error': '<?=GetMessageJS("admin_forgot_password_error")?>',
	'admin_change_password_error': '<?=GetMessageJS("admin_change_password_error")?>',
	'admin_authorize_info': '<?=GetMessageJS("admin_authorize_info")?>'
});

new BX.adminLogin({
	form: 'form_auth',
	start_form: '<?=CUtil::JSEscape($inc_file)?>',
	post_data: '<?=CUtil::JSEscape($post_data)?>',
	popup_alignment: 'popup_alignment',
	login_wrapper: 'login_wrapper',
	window_wrapper: 'window_wrapper',
	auth_form_wrapper: 'auth_form_wrapper',
	login_variants: 'login_variants',
	url: '<?echo CUtil::JSEscape($sDocPath.(($s=DeleteParam(array("logout", "login"))) == ""? "":"?".$s));?>'
});
</script>

	<table class="login-popup-alignment">
		<tr>
			<td class="login-popup-alignment-2" id="popup_alignment">
				<div class="login-header">
					<a href="/" class="login-logo">
						<span class="login-logo-img"></span><span class="login-logo-text"><?=$_SERVER["SERVER_NAME"]?></span>
					</a>
					<div class="login-language-btn-wrap"><div class="login-language-btn" id="login_lang_button"><?=$arLangButton['TEXT']?></div></div>
				</div>

				<div class="login-footer">
					<div class="login-footer-left"><?=$sCopyright?></div>
					<div class="login-footer-right">
						<?if(($siteSupport = getLocalPath("php_interface/this_site_support.php", BX_PERSONAL_ROOT)) !== false):?><?include($_SERVER["DOCUMENT_ROOT"].$siteSupport);?><?else:?><?echo $sLinks?><?endif;?>
					</div>
				</div>
				<form name="form_auth" method="post" target="auth_frame" class="bx-admin-auth-form" action="" novalidate>
					<input type="hidden" name="AUTH_FORM" value="Y">

					<div id="auth_form_wrapper"><?require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/auth/".$inc_file.'.php')?></div>

					<?=bitrix_sessid_post()?>
				</form>
			</td>
		</tr>
	</table>

<iframe name="auth_frame" src="" style="display:none;"></iframe>

<div id="login_variants" style="display: none;">
<?
foreach ($arFormsList as $form)
{
	if ($form != $inc_file)
	{
		require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/auth/".$form.".php");
	}
}
?>

<div id="forgot_password_message" class="login-popup-wrap login-popup-ifo-wrap">
	<div class="login-popup">
		<div class="login-popup-title"><?=GetMessage('AUTH_FORGOT_PASSWORD')?></div>
		<div class="login-popup-title-description"><?=GetMessage("AUTH_GET_CHECK_STRING_SENT")?></div>
		<div class="login-popup-message-wrap">
			<div class="adm-info-message-wrap adm-info-message-green">
				<div class="adm-info-message" id="forgot_password_message_inner"></div>
			</div>
		</div>
		<a class="login-popup-link" href="javascript:void(0)" onclick="BX.adminLogin.toggleAuthForm('change_password')"><?=GetMessage('AUTH_GOTO_CHANGE_FORM')?></a>
	</div>
</div>

<div id="change_password_message" class="login-popup-wrap login-popup-ifo-wrap">
	<div class="login-popup">
		<div class="login-popup-title"><?=GetMessage('AUTH_CHANGE_PASSWORD')?></div>
		<div class="login-popup-message-wrap">
			<div class="adm-info-message-wrap adm-info-message-green">
				<div class="adm-info-message" id="change_password_message_inner"></div>
			</div>
		</div>
		<a class="login-popup-link" href="javascript:void(0)" onclick="BX.adminLogin.toggleAuthForm('authorize')"><?=GetMessage('AUTH_GOTO_AUTH_FORM')?></a>
	</div>
</div>

</div>
<?
if ($arAuthResult)
{
	$bOnHit = true;
	include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/auth/wrapper_auth_result.php");
}
auth/authorize.php000064400000010665147732346240010254 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

$store_password = COption::GetOptionString("main", "store_password", "Y");
$bNeedCaptcha = $APPLICATION->NeedCAPTHAForLogin($last_login);

$authLink = false;
if(
	\Bitrix\Main\Loader::includeModule("socialservices")
	&& class_exists("Bitrix\\Socialservices\\Network") // just to check if socserv update installed
	&& method_exists("Bitrix\\Socialservices\\Network", "displayAdminPopup")
)
{
	$authLink = \Bitrix\Socialservices\Network::getAuthUrl("popup", array("admin"));
}
?>

<div class="login-main-popup-wrap login-popup-wrap<?=$bNeedCaptcha?" login-captcha-popup-wrap" : ""?>" id="authorize">
	<input type="hidden" name="TYPE" value="AUTH">
	<div class="login-popup">
		<div class="login-popup-title"><?=GetMessage('AUTH_TITLE')?></div>
		<div class="login-popup-title-description"><?=GetMessage("AUTH_PLEASE_AUTH")?></div>

		<div class="login-popup-field">
			<div class="login-popup-field-title"><?=GetMessage("AUTH_LOGIN")?></div>
			<div class="login-input-wrap">
				<input type="text" class="login-input" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="USER_LOGIN" value="<?echo htmlspecialcharsbx($last_login)?>" tabindex="1">
				<div class="login-inp-border"></div>
			</div>
		</div>
		<div class="login-popup-field" id="authorize_password">
			<div class="login-popup-field-title"><?=GetMessage("AUTH_PASSWORD")?></div>
			<div class="login-input-wrap">
				<input type="password" class="login-input" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="USER_PASSWORD" tabindex="2">
				<div class="login-inp-border"></div>
			</div>
			<input type="submit" value="" class="login-btn-green" name="Login" tabindex="4" onfocus="BX.addClass(this, 'login-btn-green-hover');" onblur="BX.removeClass(this, 'login-btn-green-hover')">
			<div class="login-loading">
				<img class="login-waiter" alt="" src="/bitrix/panel/main/images/login-waiter.gif">
			</div>
		</div>
<?
$CAPTCHA_CODE = '';
if($bNeedCaptcha)
{
	$CAPTCHA_CODE = $APPLICATION->CaptchaGetCode();
}

?>
		<input type="hidden" name="captcha_sid" value="<?=$CAPTCHA_CODE?>" />
		<div class="login-popup-field login-captcha-field">
			<div class="login-popup-field-title"><?=GetMessage("AUTH_CAPTCHA_PROMT")?></div>
			<div class="login-input-wrap">
				<span class="login-captcha-wrap" id="captcha_image"><?if($bNeedCaptcha):?><img src="/bitrix/tools/captcha.php?captcha_sid=<?=$CAPTCHA_CODE?>" width="180" height="40" alt="CAPTCHA" /><?endif;?></span><input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="captcha_word" class="login-input" tabindex="5" autocomplete="off">
				<div class="login-inp-border"></div>
			</div>
		</div>
<?

if($store_password=="Y"):
	?>
	<div class="login-popup-checbox-block">
		<input type="checkbox" class="adm-designed-checkbox" id="USER_REMEMBER" name="USER_REMEMBER" value="Y" tabindex="3" onfocus="BX.addClass(this.nextSibling, 'login-popup-checkbox-label-active')" onblur="BX.removeClass(this.nextSibling, 'login-popup-checkbox-label-active')"><label for="USER_REMEMBER" class="adm-designed-checkbox-label"></label>
		<label for="USER_REMEMBER" class="login-popup-checkbox-label"><?=GetMessage("AUTH_REMEMBER_ME")?></label>
	</div>
	<?
endif;

if($not_show_links!="Y"):
?>
		<a class="login-popup-link login-popup-forget-pas" href="javascript:void(0)" onclick="BX.adminLogin.toggleAuthForm('forgot_password')"><?=GetMessage("AUTH_FORGOT_PASSWORD_2")?></a>
<?
endif;
?>

<?
if($authLink):
	$lang = LANGUAGE_ID == 'ua'
		? LANGUAGE_ID :
		\Bitrix\Main\Localization\Loc::getDefaultLang(LANGUAGE_ID);
?>
		<div class="login-popup-field login-auth-serv-icons">
			<a href="" class="login-ss-button bitrix24net-button bitrix24net-button-ru"></a>
		</div>
	<div class="login-popup-network-block">
		<span class="login-popup-network-label"><?=GetMessage("AUTH_NW_SECTION")?></span>
		<span class="login-popup-network-btn login-popup-network-btn-<?=$lang?>" onclick="BX.util.popup('<?=CUtil::JSEscape($authLink)?>', 800, 600);"></span>
	</div>
<?
endif;
?>

	</div>
</div>
<script type="text/javascript">
BX.adminLogin.registerForm(new BX.authFormAuthorize('authorize', {url: '<?echo CUtil::JSEscape($authUrl."?login=yes".(($s=DeleteParam(array("logout", "login"))) == ""? "":"&".$s));?>'}));
</script>
auth/forgot_password.php000064400000006016147732346240011457 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

$bNeedCaptcha = (COption::GetOptionString("main", "captcha_restoring_password", "N") == "Y");
?>

<div id="forgot_password" class="login-popup-wrap-with-text">
	<div class="login-popup-wrap login-popup-request-wrap">
		<input type="hidden" name="TYPE" value="SEND_PWD">
		<div class="login-popup">
			<div class="login-popup-title"><?=GetMessage('AUTH_FORGOT_PASSWORD')?></div>
			<div class="login-popup-title-description"><?=GetMessage("AUTH_GET_CHECK_STRING")?></div>
			<div class="login-popup-request-fields-wrap" id="forgot_password_fields">
				<div class="login-popup-field">
					<div class="login-popup-field-title"><?=GetMessage("AUTH_LOGIN")?></div>
					<div class="login-input-wrap">
						<input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" class="login-input"  name="USER_LOGIN" value="<?echo htmlspecialcharsbx($last_login)?>">
						<div class="login-inp-border"></div>
					</div>
				</div>
				<div class="login-popup-either"><?=GetMessage("AUTH_OR")?></div>
				<div class="login-popup-field">
					<div class="login-popup-field-title">E-mail</div>
					<div class="login-input-wrap">
						<input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" class="login-input" name="USER_EMAIL">
						<div class="login-inp-border"></div>
					</div>
				</div>
				<input type="hidden" name="captcha_sid" value="" />
				<div class="login-popup-field login-captcha-field">
					<div class="login-popup-field-title"><?=GetMessage("AUTH_CAPTCHA_PROMT")?></div>
					<div class="login-input-wrap">
						<span class="login-captcha-wrap" id="captcha_image"></span><input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="captcha_word" class="login-input" tabindex="5" autocomplete="off">
						<div class="login-inp-border"></div>
					</div>
				</div>
			</div>
			<div class="login-btn-wrap" id="forgot_password_message_button"><a class="login-popup-link login-popup-return-auth" href="javascript:void(0)" onclick="BX.adminLogin.toggleAuthForm('authorize')"><?=GetMessage('AUTH_GOTO_AUTH_FORM_1')?></a><input type="submit" value="<?=GetMessage("AUTH_SEND")?>" class="login-btn" name="send_account_info"></div>
		</div>
	</div>
	<div class="login-popup-request-text" id="forgot_password_note">
		<?=GetMessage("AUTH_FORGOT_PASSWORD_1")?><br>
	</div>
</div>

<script type="text/javascript">
var obForgMsg = new BX.authFormForgotPasswordMessage('forgot_password_message', {url:''}),
	obForg = new BX.authFormForgotPassword('forgot_password', {
		url: '<?echo CUtil::JSEscape($authUrl."?forgot_password=yes".(($s=DeleteParam(array("forgot_password"))) == ""? "":"&".$s))?>',
		needCaptcha: <?=$bNeedCaptcha?'true':'false'?>,
		message: obForgMsg
});
BX.adminLogin.registerForm(obForg);
BX.adminLogin.registerForm(obForgMsg);
</script>
auth/change_password.php000064400000007674147732346240011417 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

$login = (strlen($USER_LOGIN)>0) ? $USER_LOGIN : $last_login;
$bNeedCaptcha = (COption::GetOptionString("main", "captcha_restoring_password", "N") == "Y");
?>

<div id="change_password" class="login-popup-wrap login-popup-replace-wrap">
	<input type="hidden" name="TYPE" value="CHANGE_PWD">
	<div class="login-popup">
		<div class="login-popup-title"><?=GetMessage("AUTH_CHANGE_PASSWORD")?></div>
		<div class="login-popup-title-description"><?=GetMessage('AUTH_CHANGE_PASSWORD_1')?></div>
		<div class="login-popup-replace-fields-wrap" id="change_password_fields">
			<div class="login-popup-field">
				<div class="login-popup-field-title"><?=GetMessage("AUTH_LOGIN")?></div>
				<div class="login-input-wrap">
					<input type="email" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" class="login-input" name="USER_LOGIN" value="<?echo htmlspecialcharsbx($login)?>">
					<div class="login-inp-border"></div>
				</div>
			</div>
			<div class="login-popup-field">
				<div class="login-popup-field-title"><?=GetMessage("AUTH_CHECKWORD")?></div>
				<div class="login-input-wrap">
					<input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" class="login-input" name="USER_CHECKWORD" value="<?echo htmlspecialcharsbx($USER_CHECKWORD)?>">
					<div class="login-inp-border"></div>
				</div>
			</div>
			<div class="login-popup-field login-replace-field">
				<div class="login-popup-field-title"><span class="login-replace-title"><?=GetMessage("AUTH_NEW_PASSWORD")?></span><span class="login-replace-title"><?=GetMessage("AUTH_NEW_PASSWORD_CONFIRM")?></span></div>
				<div class="login-input-wrap">
					<input type="password" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" class="login-input" name="USER_PASSWORD"><input type="password" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" class="login-input" name="USER_CONFIRM_PASSWORD">
					<div class="login-inp-border"></div>
				</div>
			</div>
			<input type="hidden" name="captcha_sid" value="" />
			<div class="login-popup-field login-captcha-field">
				<div class="login-popup-field-title"><?=GetMessage("AUTH_CAPTCHA_PROMT")?></div>
				<div class="login-input-wrap">
					<span class="login-captcha-wrap" id="captcha_image"></span><input type="text" onfocus="BX.addClass(this.parentNode, 'login-input-active')" onblur="BX.removeClass(this.parentNode, 'login-input-active')" name="captcha_word" class="login-input" tabindex="5" autocomplete="off">
					<div class="login-inp-border"></div>
				</div>
			</div>
		</div>
		<a href="javascript:void(0)" onclick="toggleAuthForm('forgot_password')" style="display: none;" id="change_password_forgot_link" class="login-popup-forget-pas"><?echo GetMessage("AUTH_GOTO_FORGOT_FORM")?></a>
		<div class="login-btn-wrap" id="change_password_button"><a class="login-popup-link login-popup-return-auth" href="javascript:void(0)" onclick="BX.adminLogin.toggleAuthForm('authorize')"><?=GetMessage('AUTH_GOTO_AUTH_FORM_1')?></a><input type="submit" name="change_pwd" value="<?=GetMessage("AUTH_CHANGE")?>" class="login-btn"></div>
	</div>
</div>

<script type="text/javascript">
BX.message({
	'AUTH_NEW_PASSWORD_CONFIRM_WRONG':'<?=GetMessageJS('AUTH_NEW_PASSWORD_CONFIRM_WRONG')?>'
});

var obChangeMsg = new BX.authFormChangePasswordMessage('change_password_message', {url:''}),
	obChange = new BX.authFormChangePassword('change_password', {
		url: '<?echo CUtil::JSEscape($authUrl."?change_password=yes".(($s=DeleteParam(array("change_password"))) == ""? "":"&".$s))?>',
		needCaptcha: <?=$bNeedCaptcha?'true':'false'?>,
		message: obChangeMsg
});
BX.adminLogin.registerForm(obChange);
BX.adminLogin.registerForm(obChangeMsg);
</script>
prolog_popup_admin.php000064400000001543147732346240011171 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
?>
<!DOCTYPE html>
<html id="bx-admin-prefix">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?echo $APPLICATION->GetTitle()?></title>
<meta http-equiv="Content-Type" content="text/html; charset=<?echo LANG_CHARSET?>">
<?
if(!is_object($adminPage))
	$adminPage = new CAdminPage();

CJSCore::Init(array('admin_interface'));

$APPLICATION->AddBufferContent(array($adminPage, "ShowCSS"));
echo $adminPage->ShowScript();
$APPLICATION->ShowHeadStrings();
$APPLICATION->ShowHeadScripts();
?>
<script type="text/javascript">
function PopupOnKeyPress(e)
{
	if(!e) e = window.event
	if(!e) return;
	if(e.keyCode == 27)
		window.close();
}
jsUtils.addEvent(window, "keypress", PopupOnKeyPress);
</script>
</head>
<body class="body-popup adm-workarea" onkeypress="PopupOnKeyPress();">popup_auth.php000064400000007574147732346240007472 0ustar00<?
$not_show_links = "Y";

require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/auth/authorize.php");
?>

<script>
window.IsOpera = function()
{
	return (navigator.userAgent.toLowerCase().indexOf('opera') != -1);
};

window.GetParameters = function(form_name)
{
	if (null == form_name)
		var form = document.forms[this.form_name];
	else
		var form = document.forms[form_name];

	if(!form)
		return "";

	var i, s = "";
	var n = form.elements.length;
	var delim = '';
	for(i=0; i<n; i++)
	{
		if (s != '') delim = '&';

		var el = form.elements[i];
		if (el.disabled)
			continue;
		switch(el.type.toLowerCase())
		{
			case 'text':
			case 'textarea':
			case 'password':
			case 'hidden':
				if (null == form_name && el.name.substr(el.name.length-4) == '_alt' && form.elements[el.name.substr(0, el.name.length-4)])
					break;
				s += delim + el.name + '=' + jsUtils.urlencode(el.value);
				break;
			case 'radio':
				if(el.checked)
					s += delim + el.name + '=' + jsUtils.urlencode(el.value);
				break;
			case 'checkbox':
				s += delim + el.name + '=' + jsUtils.urlencode(el.checked ? 'Y':'N');
				break;
			case 'select-one':
				var val = "";
				if (null == form_name && form.elements[el.name + '_alt'] && el.selectedIndex == 0)
					val = form.elements[el.name+'_alt'].value;
				else
					val = el.value;
				s += delim + el.name + '=' + jsUtils.urlencode(val);
				break;
			case 'select-multiple':
				var j;
				var l = el.options.length;
				for (j=0; j<l; j++)
					if (el.options[j].selected)
						s += delim + el.name + '=' + jsUtils.urlencode(el.options[j].value);
				break;
			default:
				break;
		}
	}
	return s;
};

window.BXAuthForm = function()
{
	var form = document.forms["form_auth"];
	if (!form)
		return;
	var editorDialogDiv = document.getElementById("BX_editor_dialog");

	if (!window.BX && top.BX)
		window.BX = top.BX;

	if (window != top)
	{
		top.originalName = top.jsPopup.form_name;
		top.jsPopup.form_name = "form_auth";

		top.obDiv = top.document.createElement('DIV');

		if (IsOpera() || !document.attachEvent)
		{
			top.obForm = form.cloneNode(true);
		}
		else
		{
			top.obForm = top.document.createElement('FORM');
			top.obForm.innerHTML = form.innerHTML;
		}

		if (!top.jsPopup.div)
			return BX.reload();

		var offset = top.jsPopup.div.firstChild.offsetHeight;

		top.obDiv.style.position = 'absolute';
		top.obDiv.style.zIndex = 1000;
		top.obDiv.style.top = (offset + 1) + 'px';
		top.obDiv.style.left = '0px';

		top.obDiv.style.backgroundColor = '#F9FAFD';
		top.obDiv.style.height = (top.jsPopup.div.offsetHeight - offset - 2) + 'px';
		top.obDiv.style.width = (top.jsPopup.div.offsetWidth - 2) + 'px';

		top.jsPopup.div.appendChild(top.obDiv);
		top.obDiv.appendChild(top.obForm);

		top.obForm.name = form.name;
		top.obForm.action = form.action;
		top.obForm.method = 'POST';

		top.obForm.target = 'file_edit_form_target';
		top.obForm.onsubmit = function() {top.ShowWaitWindow(); top.jsPopup.form_name = top.originalName; return true;};
		top.obForm.USER_LOGIN.focus();

		top.CloseWaitWindow();
	}
	else if(editorDialogDiv) // Handle authorization lost in editor dialogs
	{
		editorDialogDiv.style.width = "520px";
		editorDialogDiv.childNodes[1].style.paddingLeft = "10px";
		editorDialogDiv.childNodes[1].style.backgroundColor = "#F9FAFD";

		document.getElementById('BX_editor_dialog_title').innerHTML = '<?=GetMessage("AUTH_PLEASE_AUTH")?>';
		jsFloatDiv.AdjustShadow(editorDialogDiv);

		form.onsubmit = function()
		{
			var r = new JCHttpRequest();
			r.Action = function(){jsUtils.onCustomEvent('onEditorLostSession');};
			r.Post('/bitrix/admin/fileman_admin.php?login=yes', window.GetParameters('form_auth'));
			return false;
		};
	}
	else
	{
		var originaName = jsPopup.form_name;
		jsPopup.form_name = "form_auth";
		form.onsubmit = function() {jsPopup.PostParameters("login=yes"); jsPopup.form_name = originaName; return false;};
	}
}

BXAuthForm();
</script>lang_files.php000066400000001204147732346240007373 0ustar00<?php
if(!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED!==true) die();

if (defined('NO_LANG_FILES') || !\Bitrix\Main\Loader::includeModule('translate'))
{
	return;
}
/** @global \CMain $APPLICATION */
if ($APPLICATION->GetGroupRight("translate") <= "D")
{
	return;
}

if (isset($_GET["show_lang_files"]) && in_array(strtoupper($_GET["show_lang_files"]), ['Y', 'N']))
{
	$_SESSION["SHOW_LANG_FILES"] = strtoupper($_GET["show_lang_files"]) === 'Y' ? 'Y' : 'N';
}

if (
	class_exists('\\Bitrix\\Translate\\Ui\\Panel') &&
	method_exists('\\Bitrix\\Translate\\Ui\\Panel', 'showLoadedFiles')
)
{
	\Bitrix\Translate\Ui\Panel::showLoadedFiles();
}filter_act.php000064400000004414147732346240007410 0ustar00<?
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

$res = false;

if($USER->IsAuthorized() && check_bitrix_sessid())
{
	$uid = $USER->GetID();
	$isAdmin = $USER->CanDoOperation('edit_other_settings');

	switch ($_REQUEST["action"])
	{
		case "save_filter":

			CUtil::decodeURIComponent($_POST);

			$arFields = array(
					"USER_ID" => $uid,
					"FILTER_ID" => $_POST['filter_id'],
					"NAME" => $_POST["name"],
					"LANGUAGE_ID" => LANG
				);

			$arFields["FIELDS"] = $_POST['fields'];

			if(isset($_POST['common']))
				$arFields["COMMON"] = $isAdmin ? $_POST['common'] : "N";

			if(isset($_POST['preset_id']))
				$arFields["PRESET_ID"] = $_POST['preset_id'];

			if(isset($_POST['sort']))
				$arFields["SORT"] = $_POST['sort'];

			if(isset($_POST['sort_field']))
				$arFields["SORT_FIELD"] = $_POST['sort_field'];

			$id = false;

			if(isset($_POST['id']))
			{
				$dbRes = CAdminFilter::GetList( array(), array("ID" => $_POST['id']), false);

				if($dbRes && $arFilter = $dbRes->Fetch())
					if(($arFilter["USER_ID"] = $uid || $isAdmin) && $arFilter["PRESET"]!="Y")
						if(CAdminFilter::Update($_POST['id'], $arFields ))
							$id = $_POST['id'];
			}
			else
				$id = CAdminFilter::Add( $arFields );

			if($id)
				$res = $id;

			break;

		case "del_filter":

			$dbRes = CAdminFilter::GetList(array(),array("ID" => $_REQUEST["id"]),false);

			$arFlt = $dbRes->GetNext();

			if(($arFlt["USER_ID"] == $uid || $isAdmin) && $arFlt["PRESET"]!="Y")
				$res = CAdminFilter::Delete($_REQUEST["id"]) ? true : false;

			break;

		case "open_tab_save":

			if(isset($_REQUEST["id"]) && isset($_REQUEST["filter_id"]))
				$_SESSION[CAdminFilter::SESS_PARAMS_NAME][$_REQUEST["filter_id"]]["activeTabId"] = $_REQUEST["id"];

			$res = true;

			break;

		case "filtered_tab_save":

			if(isset($_REQUEST["id"]) && isset($_REQUEST["filter_id"]))
			{
				if($_REQUEST["id"] != "false")
					$_SESSION[CAdminFilter::SESS_PARAMS_NAME][$_REQUEST["filter_id"]]["filteredId"] = $_REQUEST["id"];
				else
					unset($_SESSION[CAdminFilter::SESS_PARAMS_NAME][$_REQUEST["filter_id"]]["filteredId"]);
			}

			$res = true;

			break;
	}
}

echo $res;
?>admin_ui_list.php000066400000141460147732346240010121 0ustar00<?
use Bitrix\Main\Text\HtmlFilter;
use Bitrix\Main\Grid\Editor\Types;
use Bitrix\Main\Grid\Panel;
use Bitrix\Main\UI\Filter\Options;
use Bitrix\Main\Grid\Context;
use Bitrix\Main\UI\PageNavigation;
use Bitrix\Main\Grid;

class CAdminUiList extends CAdminList
{
	public $enableNextPage = false;
	public $totalRowCount = 0;

	protected $filterPresets = array();
	protected $currentPreset = array();

	private $isShownContext = false;
	private $contextSettings = array();

	/** @var CAdminUiContextMenu */
	public $context = false;

	public function AddHeaders($aParams)
	{
		parent::AddHeaders($aParams);
		$this->SetVisibleHeaderColumn();
	}

	public function SetVisibleHeaderColumn()
	{
		$gridOptions = new Bitrix\Main\Grid\Options($this->table_id);
		$gridColumns = $gridOptions->GetVisibleColumns();
		if ($gridColumns)
		{
			$this->arVisibleColumns = array();
			$this->aVisibleHeaders = array();
			foreach ($gridColumns as $columnId)
			{
				if (isset($this->aHeaders[$columnId]) && !isset($this->aVisibleHeaders[$columnId]))
				{
					$this->arVisibleColumns[] = $columnId;
					$this->aVisibleHeaders[$columnId] = $this->aHeaders[$columnId];
				}
			}
		}
	}

	/**
	 * @param $navigationId
	 *
	 * @return PageNavigation
	 */
	public function getPageNavigation($navigationId)
	{
		$pageNum = 1;

		if (!Context::isInternalRequest()
			&& !(isset($_REQUEST["clear_nav"]) && $_REQUEST["clear_nav"] === "Y")
			&& isset($_SESSION["ADMIN_PAGINATION_DATA"])
			&& isset($_SESSION["ADMIN_PAGINATION_DATA"][$this->table_id])
		)
		{
			$paginationData = $_SESSION["ADMIN_PAGINATION_DATA"][$this->table_id];
			if (isset($paginationData["PAGE_NUM"]))
			{
				$pageNum = (int)$paginationData["PAGE_NUM"];
			}
		}

		$nav = new PageNavigation($navigationId);
		$nav->setPageSize($this->getNavSize());
		$nav->setCurrentPage($pageNum);
		$nav->initFromUri();

		if (Context::isInternalRequest())
		{
			if (!isset($_SESSION["ADMIN_PAGINATION_DATA"]))
			{
				$_SESSION["ADMIN_PAGINATION_DATA"] = array();
			}
			$_SESSION["ADMIN_PAGINATION_DATA"][$this->table_id] = array("PAGE_NUM" => $nav->getCurrentPage());
		}

		return $nav;
	}

	public function isTotalCountRequest()
	{
		$request = Bitrix\Main\Context::getCurrent()->getRequest();
		if ($request->isAjaxRequest() && $request->get("action") == "getTotalCount")
		{
			return true;
		}
		return false;
	}

	public function sendTotalCountResponse($totalCount)
	{
		global $adminAjaxHelper;
		if (!is_object($adminAjaxHelper))
		{
			require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");
			$adminAjaxHelper = new CAdminAjaxHelper();
		}

		$adminAjaxHelper->sendJsonResponse(["totalCountHtml" => GetMessage("admin_lib_list_all_title").": ".(int) $totalCount]);
	}

	public function SetNavigationParams(\CAdminUiResult $queryObject, $params = array())
	{
		if ($this->isPublicMode)
		{
			unset($params["BASE_LINK"]);
		}
		$queryObject->setNavigationParams($params);
		$this->NavText($queryObject->GetNavPrint(""));
		$this->totalRowCount = $queryObject->NavRecordCount;
		$this->enableNextPage = $queryObject->PAGEN < $queryObject->NavPageCount;
	}

	public function setNavigation(\Bitrix\Main\UI\PageNavigation $nav, $title, $showAllways = true, $post = false)
	{
		global $APPLICATION;

		$this->totalRowCount = $nav->getRecordCount();
		$this->enableNextPage = $nav->getCurrentPage() < $nav->getPageCount();

		ob_start();

		$APPLICATION->IncludeComponent(
			"bitrix:main.pagenavigation",
			"grid",
			array(
				"NAV_OBJECT" => $nav,
				"TITLE" => $title,
				"SHOW_ALWAYS" => $showAllways,
				"POST" => $post,
				"TABLE_ID" => $this->table_id,
			),
			false,
			array(
				"HIDE_ICONS" => "Y",
			)
		);

		$this->NavText(ob_get_clean());
	}

	public function getCurPageParam($strParam="", $arParamKill=array(), $get_index_page=null)
	{
		global $APPLICATION;

		if (Context::isInternalRequest())
		{
			$arParamKill = array_merge($arParamKill, array("internal", "grid_id", "grid_action", "bxajaxid", "sessid"));
		}

		return $APPLICATION->GetCurPageParam($strParam, $arParamKill, $get_index_page);
	}

	public function getNavSize()
	{
		$gridOptions = new Bitrix\Main\Grid\Options($this->table_id);
		$navParams = $gridOptions->getNavParams();
		return $navParams["nPageSize"];
	}

	public function EditAction()
	{
		if(
			$_SERVER["REQUEST_METHOD"] == "POST" &&
			!empty($_REQUEST["action_button_".$this->table_id]) &&
			is_array($_POST["FIELDS"]) &&
			check_bitrix_sessid()
		)
		{
			$arrays = array(&$_POST, &$_REQUEST, &$GLOBALS);
			foreach ($arrays as $i => &$array)
			{
				$customFields = [];
				foreach ($array["FIELDS"] as $id => &$fields)
				{
					if (is_array($fields))
					{
						CUtil::decodeURIComponent($fields);
						$keys = array_keys($fields);
						foreach ($keys as $key)
						{
							if (preg_match("/_custom/i", $key, $match))
							{
								if (!is_array($arrays[$i]["FIELDS"][$id][$key]))
								{
									continue;
								}
								foreach ($arrays[$i]["FIELDS"][$id][$key] as $index => $value)
								{
									if (!isset($value["name"]) || !isset($value["value"]))
									{
										continue;
									}
									if (preg_match_all("/(.*?)\[(.*?)\]/", $value["name"], $listMatchKeys))
									{
										$listPreparedKeys = [];
										foreach ($listMatchKeys as $matchKeys)
										{
											foreach ($matchKeys as $matchKey)
											{
												if (!is_string($matchKey) || strlen(trim($matchKey)) == 0)
												{
													continue;
												}
												if (strpos($matchKey, "[") === false && strpos($matchKey, "]") === false)
												{
													$listPreparedKeys[] = $matchKey;
												}
											}
										}
										$listPreparedKeys[] = $value["value"];
										$customFields = array_replace_recursive($customFields, $this->prepareCustomKey(
											array_shift($listPreparedKeys), $listPreparedKeys));
									}
								}
								unset($arrays[$i]["FIELDS"][$id][$key]);
							}

							if(($c = substr($key, 0, 1)) == '~' || $c == '=')
							{
								unset($arrays[$i]["FIELDS"][$id][$key]);
							}
						}
					}
				}
				if ($customFields)
				{
					$arrays[$i] = array_replace_recursive($arrays[$i], $customFields);
				}
			}
			return true;
		}
		return false;
	}

	private function prepareCustomKey($key, array $keys)
	{
		return (count($keys) == 1 ? [$key => array_shift($keys)] :
			[$key => $this->prepareCustomKey(array_shift($keys), $keys)]);
	}

	/**
	 * @return array|false
	 */
	public function GroupAction()
	{
		$this->PrepareAction();

		if ($this->GetAction() === null)
		{
			return false;
		}

		if (!check_bitrix_sessid())
		{
			return false;
		}

		if (!empty($_REQUEST["bxajaxid"]))
		{
			global $adminSidePanelHelper;
			$adminSidePanelHelper->setSkipResponse(true);
		}

		if (!$this->IsGroupActionToAll())
		{
			$arID = $this->GetGroupIds();
			if ($arID === null)
			{
				$arID = false;
			}
		}
		else
		{
			$arID = array("");
		}

		return $arID;
	}

	/**
	 * Returns true if the user has set the flag "To all" in the list.
	 *
	 * @return bool
	 */
	public function IsGroupActionToAll()
	{
		return (
			isset($_REQUEST["action_all_rows_".$this->table_id])
			&& $_REQUEST["action_all_rows_".$this->table_id] === 'Y'
		);
	}

	/**
	 * @return void
	 */
	protected function PrepareAction()
	{
		if (isset($_REQUEST["action"]) && is_array($_REQUEST["action"]))
		{
			foreach ($_REQUEST["action"] as $actionKey => $actionValue)
				$_REQUEST[$actionKey] = $actionValue;
		}
		if (!empty($_REQUEST["action_button_".$this->table_id]))
		{
			$_REQUEST["action"] = $_REQUEST["action_button_".$this->table_id];
			$_REQUEST["action_button"] = $_REQUEST["action_button_".$this->table_id];
		}
	}

	public function ActionDoGroup($id, $action_id, $add_params = "")
	{
		$listParams = explode("&", $add_params);
		$addParams = array();
		if ($listParams)
		{
			foreach($listParams as $param)
			{
				$explode = explode("=", $param);
				if ($explode[0] && $explode[1])
				{
					$addParams[$explode[0]] = $explode[1];
				}
			}
		}

		$postParams = array_merge(array(
			"action_button_".$this->table_id => $action_id,
			"ID" => $id
		), $addParams);

		return $this->ActionAjaxPostGrid($postParams);
	}

	public function ActionAjaxPostGrid($postParams)
	{
		return "BX.Main.gridManager.getById('".$this->table_id."').instance.reloadTable('POST', ".
			CUtil::PhpToJsObject($postParams).");";
	}

	public function AddFilter(array $filterFields, array &$arFilter)
	{
		$filterOption = new Bitrix\Main\UI\Filter\Options($this->table_id);
		$filterData = $filterOption->getFilter($filterFields);
		$filterable = array();
		$quickSearchKey = "";
		foreach ($filterFields as $filterField)
		{
			if (isset($filterField["quickSearch"]))
			{
				$quickSearchKey = $filterField["quickSearch"].$filterField["id"];
			}
			$filterable[$filterField["id"]] = $filterField["filterable"];
		}

		foreach ($filterData as $fieldId => $fieldValue)
		{
			if ((is_array($fieldValue) && empty($fieldValue)) || (is_string($fieldValue) && strlen($fieldValue) <= 0))
			{
				continue;
			}

			if (substr($fieldId, -5) == "_from")
			{
				$realFieldId = substr($fieldId, 0, strlen($fieldId)-5);
				if (!array_key_exists($realFieldId, $filterable))
				{
					continue;
				}
				if (substr($realFieldId, -2) == "_1")
				{
					$arFilter[$realFieldId] = $fieldValue;
				}
				else
				{
					if (!empty($filterData[$realFieldId."_numsel"]) && $filterData[$realFieldId."_numsel"] == "more")
						$filterPrefix = ">";
					else
						$filterPrefix = ">=";
					$arFilter[$filterPrefix.$realFieldId] = trim($fieldValue);
				}
			}
			elseif (substr($fieldId, -3) == "_to")
			{
				$realFieldId = substr($fieldId, 0, strlen($fieldId)-3);
				if (!array_key_exists($realFieldId, $filterable))
				{
					continue;
				}
				if (substr($realFieldId, -2) == "_1")
				{
					$realFieldId = substr($realFieldId, 0, strlen($realFieldId)-2);
					$arFilter[$realFieldId."_2"] = $fieldValue;
				}
				else
				{
					if (!empty($filterData[$realFieldId."_numsel"]) && $filterData[$realFieldId."_numsel"] == "less")
						$filterPrefix = "<";
					else
						$filterPrefix = "<=";
					$arFilter[$filterPrefix.$realFieldId] = trim($fieldValue);
				}
			}
			else
			{
				if (array_key_exists($fieldId, $filterable))
				{
					$filterPrefix = $filterable[$fieldId];
					$arFilter[$filterPrefix.$fieldId] = $fieldValue;
				}
				if ($fieldId == "FIND" && trim($fieldValue) && $quickSearchKey)
				{
					$arFilter[$quickSearchKey] = $fieldValue;
				}
			}
		}
	}

	public function hasGroupErrors()
	{
		return (bool)(count($this->arGroupErrors));
	}

	public function getGroupErrors()
	{
		$error = "";
		foreach ($this->arGroupErrors as $groupError)
		{
			$error .= " ".$groupError[0];
		}

		return trim($error);
	}

	public function setContextSettings(array $settings)
	{
		$this->contextSettings = $settings;
	}

	public function AddAdminContextMenu($aContext=array(), $bShowExcel=true, $bShowSettings=true)
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$aAdditionalMenu = array();

		if ($bShowExcel)
		{
			if ($this->contextSettings["pagePath"])
			{
				$pageParam = (!empty($_GET) ? http_build_query($_GET, "", "&") : "");
				$pagePath = $this->contextSettings["pagePath"]."?".$pageParam;
				$pageParams = array("mode" => "excel");
				if ($this->isPublicMode)
					$pageParams["public"] = "y";
				$link = CHTTP::urlAddParams($pagePath, $pageParams);
			}
			else
			{
				$link = CHTTP::urlAddParams($APPLICATION->GetCurPageParam(), array("mode" => "excel"));
			}
			$link = CHTTP::urlDeleteParams($link, ["apply_filter"]);
			$aAdditionalMenu[] = array(
				"TEXT" => "Excel",
				"TITLE" => GetMessage("admin_lib_excel"),
				"LINK" => $link,
				"GLOBAL_ICON"=>"adm-menu-excel",
			);
		}

		if (count($aContext) > 0 || count($aAdditionalMenu) > 0)
			$this->context = new CAdminUiContextMenu($aContext, $aAdditionalMenu);
	}

	private function GetGroupAction()
	{
		$actionPanelConstructor = new CAdminUiListActionPanel(
			$this->table_id, $this->arActions, $this->arActionsParams);

		return $actionPanelConstructor->getActionPanel();
	}

	public function &AddRow($id = false, $arRes = Array(), $link = false, $title = false)
	{
		$row = new CAdminUiListRow($this->aHeaders, $this->table_id);
		$row->id = ($id ? $id : randString(4));
		$row->arRes = $arRes;
		if ($this->isPublicMode)
		{
			$selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");
			$reqValue = "/".str_replace("/", "\/", $selfFolderUrl)."/i";
			if (!empty($link) && !preg_match($reqValue, $link) && preg_match("/\.php/i", $link))
			{
				$link = $selfFolderUrl.$link;
			}
		}
		$row->link = $link;
		$row->title = $title;
		$row->pList = &$this;
		$row->bEditMode = true;
		$this->aRows[] = &$row;
		return $row;
	}

	/**
	 * The method set the default fields for the filter.
	 *
	 * @param array $fields array("fieldId1", "fieldId2", "fieldId3")
	 */
	public function setDefaultFilterFields(array $fields)
	{
		$filterOptions = new Bitrix\Main\UI\Filter\Options($this->table_id);
		$filterOptions->setFilterSettings(
			"default_filter",
			array("rows" => $fields),
			false
		);
		$filterOptions->save();
	}

	/**
	 * The method set filter presets.
	 *
	 * @param array $filterPresets array("presetId" => array("name" => "presetName", "fields" => array(...)))
	 */
	public function setFilterPresets(array $filterPresets)
	{
		$this->filterPresets = $filterPresets;
		foreach ($filterPresets as $filterPreset)
		{
			if (!empty($filterPreset["current"]))
			{
				$this->currentPreset = $filterPreset;
			}
		}
	}

	public function deletePreset($presetId)
	{
		$options = new Options($this->table_id);
		$options->deleteFilter($presetId);
		$options->save();
	}

	public function DisplayFilter(array $filterFields = array())
	{
		global $APPLICATION;

		$params = array(
			"FILTER_ID" => $this->table_id,
			"GRID_ID" => $this->table_id,
			"FILTER" => $filterFields,
			"FILTER_PRESETS" => $this->filterPresets,
			"ENABLE_LABEL" => true,
			"ENABLE_LIVE_SEARCH" => true
		);

		if ($this->currentPreset)
		{
			$options = new Options($this->table_id, $this->filterPresets);
			$options->setFilterSettings($this->currentPreset["id"], $this->currentPreset, true, false);
			$options->save();
		}

		if ($this->context)
		{
			$this->context->setFilterContextParam(true);
		}

		if ($this->isPublicMode)
		{
			ob_start();
			?>
				<div class="pagetitle-container pagetitle-flexible-space">
					<?
					$APPLICATION->includeComponent(
						"bitrix:main.ui.filter",
						"",
						$params,
						false,
						array("HIDE_ICONS" => true)
					);
					?>
				</div>
			<?
			$APPLICATION->AddViewContent("inside_pagetitle", ob_get_clean());
		}
		else
		{
			$APPLICATION->SetAdditionalCSS('/bitrix/css/main/grid/webform-button.css');
			?>
			<div class="adm-toolbar-panel-container">
				<div class="adm-toolbar-panel-flexible-space">
					<?
					$APPLICATION->includeComponent(
						"bitrix:main.ui.filter",
						"",
						$params,
						false,
						array("HIDE_ICONS" => true)
					);
					?>
				</div>
				<?
				$this->ShowContext();
				?>
			</div>
			<?
		}

		$this->createFilterSelectorHandlers($filterFields);

		?>
		<script type="text/javascript">
			BX.ready(function () {
				if (!window['filter_<?=$this->table_id?>'] ||
					!BX.is_subclass_of(window['filter_<?=$this->table_id?>'], BX.adminUiFilter))
				{
					window['filter_<?=$this->table_id?>'] = new BX.adminUiFilter('<?=$this->table_id?>',
						<?=CUtil::PhpToJsObject(array())?>);
				}
			});
		</script>
		<?
	}

	private function createFilterSelectorHandlers(array $filterFields = array())
	{
		$selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");
		foreach ($filterFields as $filterField)
		{
			if (isset($filterField["type"]) && $filterField["type"] !== "custom_entity")
			{
				continue;
			}

			if (isset($filterField["selector"]) && isset($filterField["selector"]["type"]))
			{
				switch ($filterField["selector"]["type"])
				{
					case "user":
						?>
						<script>
							BX.ready(function() {
								if (!window["userFilterHandler_<?=$filterField["id"]?>"])
								{
									var params = {
										filterId: "<?=$this->table_id?>",
										fieldId: "<?=$filterField["id"]?>",
										languageId: "<?=LANGUAGE_ID?>",
										selfFolderUrl: "<?=$selfFolderUrl?>"
									};
									window["userFilterHandler_<?=$filterField["id"]?>"] =
										new BX.adminUserFilterHandler(params);
								}
							});
							if (typeof(SUVsetUserId_<?=$filterField["id"]?>) === "undefined")
							{
								function SUVsetUserId_<?=$filterField["id"]?>(userId)
								{
									if (window["userFilterHandler_<?=$filterField["id"]?>"])
									{
										var adminUserFilterHandler = window["userFilterHandler_<?=$filterField["id"]?>"];
										adminUserFilterHandler.setSelected(userId);
									}
								}
							}
						</script>
						<?
						break;
					case "product":
						?>
						<script>
							BX.ready(function() {
								if (!window["productFilterHandler_<?=$filterField["id"]?>"])
								{
									var params = {
										filterId: "<?=$this->table_id?>",
										fieldId: "<?=$filterField["id"]?>",
										languageId: "<?=LANGUAGE_ID?>",
										publicMode: "<?=($this->isPublicMode ? "Y" : "N")?>",
										selfFolderUrl: "<?=$selfFolderUrl?>"
									};
									window["productFilterHandler_<?=$filterField["id"]?>"] =
										new BX.adminProductFilterHandler(params);
								}
							});
							if (typeof(FillProductFields_<?=$filterField["id"]?>) === "undefined")
							{
								function FillProductFields_<?=$filterField["id"]?>(product)
								{
									if (window["productFilterHandler_<?=$filterField["id"]?>"])
									{
										var adminProductFilterHandler =
											window["productFilterHandler_<?=$filterField["id"]?>"];
										adminProductFilterHandler.closeProductSearchDialog();
										adminProductFilterHandler.setSelected(product["id"], product["name"]);
									}
								}
							}
						</script>
						<?
						break;
				}
			}
		}
	}

	public function ShowActionTable() {}

	public function DisplayList($arParams = array())
	{
		$arParams = array_change_key_case($arParams, CASE_UPPER);

		foreach(GetModuleEvents("main", "OnAdminListDisplay", true) as $arEvent)
			ExecuteModuleEventEx($arEvent, array(&$this));

		$errorMessage = "";
		foreach ($this->arFilterErrors as $error)
			$errorMessage .= " ".$error;
		foreach ($this->arUpdateErrors as $arError)
			$errorMessage .= " ".$arError[0];
		foreach ($this->arGroupErrors as $arError)
			$errorMessage .= " ".$arError[0];

		if (Context::isValidateRequest())
		{
			global $adminAjaxHelper;
			if (!is_object($adminAjaxHelper))
			{
				require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");
				$adminAjaxHelper = new CAdminAjaxHelper();
			}
			global $APPLICATION;
			$APPLICATION->RestartBuffer();
			if ($errorMessage)
			{
				$adminAjaxHelper->sendJsonResponse(array("messages" => array(
					array("TYPE" => Bitrix\Main\Grid\MessageType::ERROR, "TEXT" => $errorMessage)))
				);
			}
			else
			{
				$adminAjaxHelper->sendJsonResponse(array("messages" => array()));
			}
		}

		if (Context::isShowpageRequest() && $errorMessage !== '')
		{
			global $adminAjaxHelper;
			if (!is_object($adminAjaxHelper))
			{
				require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");
				$adminAjaxHelper = new CAdminAjaxHelper();
			}
			global $APPLICATION;
			$APPLICATION->RestartBuffer();

			$adminAjaxHelper->sendJsonResponse(array("messages" => array(
				array("TYPE" => Bitrix\Main\Grid\MessageType::ERROR, "TEXT" => $errorMessage)))
			);
		}

		global $APPLICATION;
		$APPLICATION->SetAdditionalCSS('/bitrix/css/main/grid/webform-button.css');

		echo $this->sPrologContent;

		$selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");

		$this->ShowContext();

		$gridParameters = array(
			"GRID_ID" => $this->table_id,
			"AJAX_MODE" => "Y",
			"AJAX_OPTION_JUMP" => "N",
			"AJAX_OPTION_HISTORY" => "N",
			"SHOW_PAGESIZE" => true,
			"AJAX_ID" => CAjax::getComponentID("bitrix:main.ui.grid", ".default", ""),
			"ALLOW_PIN_HEADER" => true,
			"ALLOW_VALIDATE" => false,
			"HANDLE_RESPONSE_ERRORS" => true
		);

		$actionPanel = (isset($arParams["ACTION_PANEL"]) ? $arParams["ACTION_PANEL"] : $this->GetGroupAction());
		if ($actionPanel)
		{
			$gridParameters["ACTION_PANEL"] = $actionPanel;
		}
		else
		{
			$gridParameters["SHOW_CHECK_ALL_CHECKBOXES"] = false;
			$gridParameters["SHOW_ROW_CHECKBOXES"] = false;
			$gridParameters["SHOW_SELECTED_COUNTER"] = false;
			$gridParameters["SHOW_ACTION_PANEL"] = false;
		}

		if (isset($arParams["SHOW_TOTAL_COUNTER"]))
		{
			$gridParameters["SHOW_TOTAL_COUNTER"] = $arParams["SHOW_TOTAL_COUNTER"];
		}

		$showTotalCountHtml = (isset($arParams["SHOW_COUNT_HTML"]) && $arParams["SHOW_COUNT_HTML"] === true);
		if ($showTotalCountHtml)
		{
			$gridParameters["TOTAL_ROWS_COUNT_HTML"] = $this->getTotalRowsCountHtml();
		}

		$gridOptions = new Bitrix\Main\Grid\Options($gridParameters["GRID_ID"]);
		$defaultSort = array();
		if ($this->sort instanceof CAdminSorting)
		{
			$defaultSort = array("sort" => array($this->sort->getField() => $this->sort->getOrder()));
		}
		$sorting = $gridOptions->GetSorting($defaultSort);
		$gridParameters["SORT"] = $sorting["sort"];
		$gridParameters["SORT_VARS"] = $sorting["vars"];

		$gridColumns = $gridOptions->getVisibleColumns();
		if (empty($gridColumns))
			$gridColumns = array_keys($this->aVisibleHeaders);

		$gridParameters["ENABLE_NEXT_PAGE"] = $this->enableNextPage;
		$gridParameters["TOTAL_ROWS_COUNT"] = $this->totalRowCount;
		if ($this->sNavText)
		{
			$gridParameters["NAV_STRING"] = $this->sNavText;
		}
		else
		{
			$gridParameters["SHOW_PAGINATION"] = false;
		}

		$gridParameters["PAGE_SIZES"] = array(
			array("NAME" => "5", "VALUE" => "5"),
			array("NAME" => "10", "VALUE" => "10"),
			array("NAME" => "20", "VALUE" => "20"),
			array("NAME" => "50", "VALUE" => "50"),
			array("NAME" => "100", "VALUE" => "100"),
			array("NAME" => "200", "VALUE" => "200"),
			array("NAME" => "500", "VALUE" => "500")
		);

		$gridParameters["ROWS"] = array();
		/** @var \CAdminUiListRow $row */
		foreach ($this->aRows as $row)
		{
			$gridRow = array(
				"id" => $row->id,
				"actions" => $row->getPreparedActions()
			);

			if ($arParams["DEFAULT_ACTION"])
			{
				if ($this->isPublicMode)
				{
					if (!empty($row->link))
					{
						$row->link = str_replace("/bitrix/admin/", $selfFolderUrl, $row->link);
					}
				}
				$gridRow["default_action"] = array();
				$gridRow["default_action"]["href"] = htmlspecialcharsback($row->link);
				if ($row->title)
					$gridRow["default_action"]["title"] = $row->title;
			}
			elseif ($row->link)
			{
				$gridRow["default_action"] = array();
				if ($this->isPublicMode)
					$gridRow["default_action"]["onclick"] = "BX.adminSidePanel.onOpenPage('".$row->link."');";
				else
					$gridRow["default_action"]["href"] = htmlspecialcharsback($row->link);
				if ($row->title)
					$gridRow["default_action"]["title"] = $row->title;
			}
			else
			{
				$gridRow["default_action"] = array();
				$gridRow["default_action"]["onclick"] = "";
			}

			foreach ($row->aFields as $fieldId => $field)
			{
				if (!empty($field["edit"]["type"]))
					$this->SetHeaderEditType($fieldId, $field);
			}

			$listEditable = array();
			foreach (array_diff_key($this->aHeaders, $row->aFields) as $fieldId => $field)
			{
				$listEditable[$fieldId] = false;
			}

			$disableEditColumns = array();

			foreach ($gridColumns as $columnId)
			{
				$field = $row->aFields[$columnId];
				if (!is_array($row->arRes[$columnId]))
					$value = trim($row->arRes[$columnId]);
				else
					$value = $row->arRes[$columnId];

				$editValue = $value;
				if (isset($field["edit"]["type"]))
				{
					switch ($field["edit"]["type"])
					{
						case "file":
							if ($fileArray = CFile::getFileArray($value))
								$editValue = $fileArray["SRC"];
							break;
						case "html":
							$editValue = $field["edit"]["value"];
							break;
					}
				}
				else
				{
					$disableEditColumns[$columnId] = false;
				}

				$gridRow["data"][$columnId] = $editValue;

				if (isset($field["view"]["type"]))
				{
					switch ($field["view"]["type"])
					{
						case "checkbox":
							if ($value == "Y")
								$value = htmlspecialcharsex(GetMessage("admin_lib_list_yes"));
							else
								$value = htmlspecialcharsex(GetMessage("admin_lib_list_no"));
							break;
						case "select":
							if ($field["edit"]["values"][$value])
								$value = htmlspecialcharsex($field["edit"]["values"][$value]);
							break;
						case "file":
							$value = $value ? CFileInput::Show("fileInput_".$value, $value,
								$field["view"]["showInfo"], $field["view"]["inputs"]) : "";
							break;
						case "html":
							$value = (strlen(trim($field["view"]["value"])) > 0 ?
								$field["view"]["value"] : (is_array($value) ? "" : $value));
							break;
						default:
							$value = htmlspecialcharsex($value);
							break;
					}
				}
				else
				{
					$value = htmlspecialcharsbx($value);
				}

				$gridRow["columns"][$columnId] = $value;
			}
			$gridRow["editable"] = $listEditable;
			if (!empty($disableEditColumns))
				$gridRow["editableColumns"] = $disableEditColumns;

			$gridParameters["ROWS"][] = $gridRow;
		}

		$gridParameters["COLUMNS"] = array();
		foreach ($this->aHeaders as $header)
		{
			$header["name"] = $header["content"];
			$gridParameters["COLUMNS"][] = $header;
		}

		if ($errorMessage <> "")
		{
			$gridParameters["MESSAGES"] = array(
				array(
					"TYPE" => Bitrix\Main\Grid\MessageType::ERROR,
					"TEXT" => $errorMessage
				)
			);
		}

		$APPLICATION->includeComponent(
			"bitrix:main.ui.grid",
			"",
			$gridParameters,
			false, array("HIDE_ICONS" => "Y")
		);

		echo $this->sEpilogContent;

		$jsParams = [];
		$jsParams["publicMode"] = $this->isPublicMode;
		$jsParams["showTotalCountHtml"] = $showTotalCountHtml;
		$jsParams["serviceUrl"] = (isset($arParams["SERVICE_URL"]) ? $arParams["SERVICE_URL"] : "");

		?>
		<script type="text/javascript">
			if (!window['<?=$this->table_id?>'] || !BX.is_subclass_of(window['<?=$this->table_id?>'], BX.adminUiList))
			{
				window['<?=$this->table_id?>'] = new BX.adminUiList(
					'<?=$this->table_id?>', <?=CUtil::PhpToJsObject($jsParams)?>);
			}
			BX.adminChain.addItems("<?=$this->table_id?>_navchain_div");
		</script>
		<?
	}

	private function getTotalRowsCountHtml()
	{
		ob_start();
		?>
			<div><?= GetMessage("admin_lib_list_all_title").": " ?>
				<a id="<?=$this->table_id?>_show_total_count" href="#"><?= GetMessage("admin_lib_list_show_row_count_title")?></a>
			</div>
		<?
		return ob_get_clean();
	}

	private function ShowContext()
	{
		if ($this->context && !$this->isShownContext)
		{
			$this->isShownContext = true;
			$this->context->Show();
		}
	}

	private function SetHeaderEditType($headerId, $field)
	{
		if (!isset($this->aHeaders[$headerId]))
		{
			return;
		}

		if (isset($this->aHeaders[$headerId]["editable"]) && $this->aHeaders[$headerId]["editable"] === false)
		{
			return;
		}

		switch ($field["edit"]["type"])
		{
			case "input":
				$editable = array("TYPE" => Types::TEXT);
				break;
			case "calendar":
				$editable = array("TYPE" => Types::DATE);
				break;
			case "checkbox":
				$editable = array("TYPE" => Types::CHECKBOX);
				break;
			case "select":
				$editable = array(
					"TYPE" => Types::DROPDOWN,
					"items" => $field["edit"]["values"]
				);
				break;
			case "file":
				$editable = array(
					"TYPE" => Types::IMAGE,
				);
				break;
			case "html":
				$editable = array("TYPE" => Types::CUSTOM, "HTML" => $field["edit"]["value"]);
				break;
			default:
				$editable = array("TYPE" => Types::TEXT);
		}

		$this->aHeaders[$headerId]["editable"] = $editable;
	}
}

/**
 * Class CAdminUiListActionPanel
 * A class for working with group actions. Allows you to create your own group actions.
	Example of use:

	// The array for $lAdmin->AddGroupActionTable($arGroupActions, $arParamsGroupActions);
	$arGroupActions['test_my_type'] = array('type' => 'my_type', 'name' => 'Check custom actions');

	$actionPanelConstructor = new CAdminUiListActionPanel(
	$this->table_id, $this->arActions, $this->arActionsParams);

	//Set your own section
	$actionPanelConstructor->setActionSections(["my_section" => []], ["default"]);
	//Set your own action type
	$actionPanelConstructor->setTypeToSectionMap(["my_type" => "my_section"]);
	//Set handler for your type
	$actionPanelConstructor->setHandlerToType(["my_type" => function ($actionKey, $action) {
		$onChange = [
			[
				"ACTION" => Panel\Actions::CREATE,
				"DATA" => [
					[
						'TYPE' => Panel\Types::CUSTOM,
						'ID' => 'my_custom_html',
						'VALUE' => '<b>Hello!</b>',
					]
				]
			]
		];
		return [
			"ID" => $actionKey,
			"TYPE" => Bitrix\Main\Grid\Panel\Types::BUTTON,
			"TEXT" => $action["name"],
			"ONCHANGE" => $onChange
		];
	}]);

	return $actionPanelConstructor->getActionPanel();
 */
class CAdminUiListActionPanel
{
	private $tableId;
	private $inputActions;
	private $inputActionsParams;

	/**
	 * @var Panel\Snippet
	 */
	private $gridSnippets;

	private $actionSections = [];
	private $mapTypesAndSections = [
		"edit" => "default",
		"delete" => "default",
		"button" => "button",
		"select" => "list",
		"customjs" => "list",
		"html" => "html",
		"for_all" => "forAll"
	];
	private $mapTypesAndHandlers = [];

	public function __construct($tableId, array $actions, array $actionsParams)
	{
		$this->tableId = $tableId;
		$this->inputActions = $actions;
		$this->inputActionsParams = $actionsParams;

		$this->gridSnippets = new Panel\Snippet();

		$this->actionSections = [
			"default" => [],
			"button" => [],
			"list" => [
				"TYPE" => Panel\Types::DROPDOWN,
				"ID" => "base_action_select_{$this->tableId}",
				"NAME" => "action_button_{$this->tableId}",
				"ITEMS" => [
					[
						"NAME" => GetMessage("admin_lib_list_actions"),
						"VALUE" => "default",
						"ONCHANGE" => [["ACTION" => Panel\Actions::RESET_CONTROLS]]
					]
				]
			],
			"html" => [],
			"forAll" => []
		];
	}

	/**
	 * The method returns an array of data of the desired format for the grid.
	 * @return array
	 */
	public function getActionPanel()
	{
		$actionPanel = [];

		$items = $this->getItems();

		$actionPanel["GROUPS"][] = array("ITEMS" => $items);

		return $actionPanel;
	}

	/**
	 * The method writes a value into an array of sections.
	 * This array is the structure of the blocks into which you place your actions.
	 * @param array $actionSections Map sections.
	 * @param array $listKeyForDelete List keys for delete default sections.
		Example:
		[
			"default" => [
				"TYPE" => Types::BUTTON,
				"ID" => "button_id",
				"CLASS" => "apply",
				"TEXT" => "My button",
				"ONCHANGE" => [
					[
						"ACTION" => Panel\Actions::CALLBACK,
						"DATA" => [
							[
								"JS" => "alert('Click!');"
							]
						]
					]
				]
			]
		];
	 */
	public function setActionSections(array $actionSections, $listKeyForDelete = [])
	{
		foreach ($listKeyForDelete as $keyForDelete)
		{
			if (isset($this->actionSections[$keyForDelete]))
			{
				unset($this->actionSections[$keyForDelete]);
			}
		}

		$this->actionSections = array_merge($this->actionSections, $actionSections);
	}

	/**
	 * The method writes values to a map of types and partitions.
	 * This makes it possible to place any type of action in a specific action section.
	 * @param array $mapTypesAndSections Map of types and sections. Example ["html" => "default"].
	 */
	public function setTypeToSectionMap(array $mapTypesAndSections)
	{
		$this->mapTypesAndSections = array_merge($this->mapTypesAndSections, $mapTypesAndSections);
	}

	/**
	 * The method writes a handler for a particular type of action. This allows you to create your own action.
	 *
	 * @param array $mapTypesAndHandlers Map of types and handlers.
	 * Example:
	 * [
		"button" => function ($actionKey, $action) {
			$onChange = [
				[
					"ACTION" => Panel\Actions::CALLBACK,
					"DATA" => [
						[
							"JS" => $action["action"] ? $action["action"] :
							"BX.adminUiList.SendSelected('{$this->tableId}')"
						]
					]
				]
			]
			return [
				"ID" => $actionKey,
				"TYPE" => Bitrix\Main\Grid\Panel\Types::BUTTON,
				"TEXT" => $action["name"],
				"ONCHANGE" => $onChange
			];
		}]
	 */
	public function setHandlerToType(array $mapTypesAndHandlers)
	{
		$this->mapTypesAndHandlers = array_merge($this->mapTypesAndHandlers, $mapTypesAndHandlers);
	}

	/**
	 * @return array
	 */
	private function getDefaultApplyAction()
	{
		return ["JS" => "BX.adminUiList.SendSelected('{$this->tableId}')"];
	}

	/**
	 * @return array
	 */
	private function getItems()
	{
		$items = [];

		$actionSections = $this->getActionSections();

		foreach ($actionSections as $actionSection)
		{
			if ($this->isAssociativeArray($actionSection))
			{
				$items[] = $actionSection;
			}
			else
			{
				foreach ($actionSection as $aSection)
				{
					$items[] = $aSection;
				}
			}
		}

		return $items;
	}

	/**
	 * @return array
	 */
	private function getActionSections()
	{
		if (isset($this->inputActions["edit"]) && isset($this->actionSections[$this->mapTypesAndSections["edit"]]))
		{
			$this->actionSections[$this->mapTypesAndSections["edit"]][] = $this->gridSnippets->getEditButton();
		}
		if (isset($this->inputActions["delete"]) && isset($this->actionSections[$this->mapTypesAndSections["delete"]]))
		{
			$this->actionSections[$this->mapTypesAndSections["delete"]][] = $this->gridSnippets->getRemoveButton();
		}

		foreach ($this->inputActions as $actionKey => $action)
		{
			$this->setActionSection($this->actionSections, $actionKey, $action);
		}

		if (isset($this->inputActions["for_all"]) && isset($this->actionSections[$this->mapTypesAndSections["for_all"]]))
		{
			$this->actionSections[$this->mapTypesAndSections["for_all"]][] = $this->gridSnippets->getForAllCheckbox();
		}

		if (count($this->actionSections["list"]["ITEMS"]) == 1)
		{
			$this->actionSections["list"] = [];
		}

		return $this->actionSections;
	}

	/**
	 * @param array &$actionSections
	 * @param string $actionKey
	 * @param string|array $action
	 * @return void
	 */
	private function setActionSection(array &$actionSections, $actionKey, $action)
	{
		if (is_array($action))
		{
			self::prepareAction($action);
			$type = $action["type"];
			$actionSection = isset($this->mapTypesAndSections[$type]) ?
				$this->mapTypesAndSections[$type] : "list";

			$method = "get".$type."ActionData";
			if ($this->mapTypesAndHandlers[$type] && is_callable($this->mapTypesAndHandlers[$type]))
			{
				$actionSections[$actionSection][] = $this->mapTypesAndHandlers[$type]($actionKey, $action);
			}
			elseif (method_exists(__CLASS__, $method))
			{
				if ($actionSection == "list")
				{
					$actionSections["list"]["ITEMS"][] = $this->$method($actionKey, $action);
				}
				else
				{
					$actionSections[$actionSection][] = $this->$method($actionKey, $action);
				}
			}
		}
		else
		{
			if (!in_array($actionKey, ["edit", "delete", "for_all"]))
			{
				$actionSections["list"]["ITEMS"][] = [
					"NAME" => $action,
					"VALUE" => $actionKey,
					"ONCHANGE" => [
						[
							"ACTION" => Panel\Actions::RESET_CONTROLS
						],
						$this->getApplyButtonCreationAction()
					]
				];
			}
		}
	}

	/**
	 * @param string $actionKey
	 * @param array $action
	 * @return array
	 */
	private function getButtonActionData($actionKey, $action)
	{
		$onChange = $action["action"] ? [
			["ACTION" => Panel\Actions::CALLBACK, "DATA" => [["JS" => $action["action"]]]]] : [];

		return [
			"ID" => $actionKey,
			"TYPE" => Bitrix\Main\Grid\Panel\Types::BUTTON,
			"TEXT" => $action["name"],
			"ONCHANGE" => $onChange
		];
	}

	/**
	 * @param string $actionKey
	 * @param array $action
	 * @return array
	 */
	private function getSelectActionData($actionKey, $action)
	{
		$internalOnchange = [];
		if (!empty($this->inputActionsParams["internal_select_onchange"]))
		{
			$internalOnchange[] = [
				"ACTION" => Panel\Actions::CALLBACK,
				"DATA" => [
					["JS" => $this->inputActionsParams["internal_select_onchange"]]
				]
			];
		}

		/**
			For each value of the list, you can pass a handler.
			example client code:
			$arGroupActions["test_section"] = array(
				"name" => "Menu item title",
				"type" => "select",
				"controlName" => "value name in request",
				"controlId" => "Dom id for dropdown control" (if empty, get from controlName),
				"items" => array(
					array("NAME" => "One", "VALUE" => "one", "ONCHANGE" => "alert('one');"),
					array("NAME" => "Two", "VALUE" => "two", "ONCHANGE" => "alert('two');")
				)
			);
		 */
		if (is_array($action["items"]))
		{
			foreach ($action["items"] as &$items)
			{
				if (empty($items["ONCHANGE"]))
				{
					$items["ONCHANGE"] = $internalOnchange;
				}
				else
				{
					$items["ONCHANGE"] = [
						[
							"ACTION" => Panel\Actions::CALLBACK,
							"DATA" => [
								["JS" => $items["ONCHANGE"]]
							]
						]
					];
				}
			}
		}

		$onchange = [
			[
				"ACTION" => Panel\Actions::RESET_CONTROLS
			],
			[
				"ACTION" => Panel\Actions::CREATE,
				"DATA" => [
					[
						"TYPE" => Panel\Types::DROPDOWN,
						"ID" => "selected_action_{$this->tableId}_".$action["controlId"],
						"NAME" => $action["controlName"],
						"ITEMS" => $action["items"]
					],
					$this->gridSnippets->getApplyButton(
						[
							"ONCHANGE" => [
								[
									"ACTION" => Panel\Actions::CALLBACK,
									"DATA" => [
										$this->getDefaultApplyAction()
									]
								]
							]
						]
					)
				]
			]
		];

		if (!empty($this->inputActionsParams["select_onchange"]))
		{
			$onchange[] = [
				"ACTION" => Panel\Actions::CALLBACK,
				"DATA" => [
					["JS" => $this->inputActionsParams["select_onchange"]]
				]
			];
		}

		return [
			"NAME" => $action["name"],
			"VALUE" => $actionKey,
			"ONCHANGE" => $onchange
		];
	}

	/**
	 * @param string $actionKey
	 * @param array $action
	 * @return array
	 */
	private function getCustomJsActionData($actionKey, $action)
	{
		return [
			"NAME" => $action["name"],
			"VALUE" => $actionKey,
			"ONCHANGE" => [
				["ACTION" => Panel\Actions::RESET_CONTROLS],
				$this->getApplyButtonCreationAction($action["js"])
			]
		];
	}

	/**
	 * @param string $actionKey
	 * @param array $action
	 * @return array
	 */
	private function getBaseActionData($actionKey, $action)
	{
		return [
			"NAME" => $action["name"],
			"VALUE" => $actionKey,
			"ONCHANGE" => [
				["ACTION" => Panel\Actions::RESET_CONTROLS],
				$this->getApplyButtonCreationAction($action["action"])
			]
		];
	}

	/**
	 * @param string $actionKey
	 * @param array $action
	 * @return array
	 */
	private function getHtmlActionData($actionKey, $action)
	{
		return [
			"ID" => $actionKey,
			"TYPE" => Panel\Types::CUSTOM,
			"VALUE" => $action["value"]
		];
	}

	/**
	 * @param string $actionKey
	 * @param array $action
	 * @return array
	 */
	private function getMultiControlActionData($actionKey, array $action)
	{
		return [
			"NAME" => $action["name"],
			"VALUE" => $actionKey,
			"ONCHANGE" => $action["action"]
		];
	}

	/**
	 * @param string $jsCallback
	 * @return array
	 */
	private function getApplyButtonCreationAction($jsCallback = "")
	{
		$action = $this->getDefaultApplyAction();
		if ($jsCallback != '')
		{
			$action["JS"] = $jsCallback;
		}
		return [
			"ACTION" => Panel\Actions::CREATE,
			"DATA" => [
				$this->gridSnippets->getApplyButton(
					[
						"ONCHANGE" => [
							[
								"ACTION" => Panel\Actions::CALLBACK,
								"DATA" => [
									$action
								]
							]
						]
					]
				)
			]
		];
	}

	/**
	 * @param $array
	 * @return bool
	 */
	private function isAssociativeArray($array)
	{
		if (!is_array($array) || empty($array))
			return false;
		return array_keys($array) !== range(0, count($array) - 1);
	}

	/**
	 * Prepare action data before add in action list.
	 *
	 * @param array &$action	Action description.
	 * return void
	 */
	private static function prepareAction(array &$action)
	{
		$action["type"] = (!empty($action["type"]) ? strtolower($action["type"]) : "base");
		if ($action["type"] == "select")
		{
			if (!isset($action["controlName"]) && isset($action["name"]))
			{
				$action["controlName"] = $action["name"];
				unset($action["name"]);
			}
			if (!isset($action["controlId"]) && isset($action["controlName"]))
			{
				$action["controlId"] = $action["controlName"];
			}
		}
		if (!isset($action["name"]))
		{
			if (isset($action["lable"]))
			{
				$action["name"] = $action["lable"];
				unset($action["lable"]);
			}
			if (isset($action["label"]))
			{
				$action["name"] = $action["label"];
				unset($action["label"]);
			}
		}
	}
}

class CAdminUiListRow extends CAdminListRow
{
	/**
	 * @return array
	 */
	public function getPreparedActions()
	{
		$result = [];
		foreach ($this->aActions as $action)
		{
			if (isset($action["SEPARATOR"]))
				continue;

			if (empty($action["ACTION"]) && !empty($action["ONCLICK"]))
			{
				$action["ACTION"] = $action["ONCLICK"];
			}

			if (!empty($action["LINK"]) && empty($action["ACTION"]))
			{
				$action["href"] = $action["LINK"];
			}
			else
			{
				if (preg_match("/BX.adminPanel.Redirect/", $action["ACTION"]))
				{
					$explode = explode("'", $action["ACTION"]);
					if (!empty($explode[1]))
						$action["href"] = $explode[1];
				}
				else
				{
					$action["ONCLICK"] = $action["ACTION"];
				}
			}

			if ($this->isPublicMode)
			{
				if (!empty($action["href"]) &&
					!preg_match("/bitrix\/admin/i", $action["href"]) && preg_match("/\.php/i", $action["href"]))
				{
					$action["href"] = "/bitrix/admin/".$action["href"];
				}
			}

			$result[] = $action;
		}
		unset($action);

		return $result;
	}
}

class CAdminUiResult extends CAdminResult
{
	protected static $navParams = [
		"totalCount" => 0,
		"totalPages" => 1,
		"pagen" => 1
	];

	private $componentParams = array();

	/**
	 * @param string $tableId
	 * @param string $className Bitrix\Main\Entity\DataManager class name.
	 * @param array $getListParams
	 */
	public static function setNavParams($tableId, $className, &$getListParams)
	{
		if (isset($_REQUEST["mode"]) && $_REQUEST["mode"] == "excel")
		{
			return;
		}

		$navyParams = CAdminUiResult::getNavParams(CAdminUiResult::getNavSize($tableId));
		if ($navyParams["SHOW_ALL"])
		{
			return;
		}
		else
		{
			$navyParams["PAGEN"] = (int)$navyParams["PAGEN"];
			$navyParams["SIZEN"] = (int)$navyParams["SIZEN"];
		}

		try
		{
			if (class_exists($className))
			{
				/**
				 * @var Bitrix\Main\Entity\DataManager $className
				 */
				$countQuery = new Bitrix\Main\Entity\Query($className::getEntity());
				$countQuery->addSelect(new Bitrix\Main\Entity\ExpressionField("CNT", "COUNT(1)"));
				$countQuery->setFilter($getListParams["filter"]);
				$totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
				unset($countQuery);
				$totalCount = (int)$totalCount["CNT"];
				$totalPages = 1;

				$navyParams = CAdminUiResult::getNavParams(CAdminUiResult::getNavSize($tableId));
				if ($totalCount > 0)
				{
					$totalPages = ceil($totalCount/ $navyParams["SIZEN"]);
					if ($navyParams["PAGEN"] > $totalPages)
					{
						$navyParams["PAGEN"] = $totalPages;
					}
				}
				else
				{
					$navyParams["PAGEN"] = 1;
				}

				self::$navParams["totalCount"] = $totalCount;
				self::$navParams["totalPages"] = $totalPages;
				self::$navParams["pagen"] = $navyParams["PAGEN"];
			}
		}
		catch (Exception $exception)
		{
			$getListParams["limit"] = $navyParams["SIZEN"];
			$getListParams["offset"] = $navyParams["SIZEN"] * ($navyParams["PAGEN"] - 1);
		}

		$getListParams["limit"] = $navyParams["SIZEN"];
		$getListParams["offset"] = $navyParams["SIZEN"] * ($navyParams["PAGEN"] - 1);
	}

	public function NavStart($nPageSize=20, $bShowAll=true, $iNumPage=false)
	{
		$nSize = $this->GetNavSize($this->table_id, $nPageSize);

		if(!is_array($nPageSize))
			$nPageSize = array();

		$nPageSize["nPageSize"] = $nSize;
		if($_REQUEST["mode"] == "excel")
			$nPageSize["NavShowAll"] = true;

		$this->nInitialSize = $nPageSize["nPageSize"];

		$this->parentNavStart($nPageSize, $bShowAll, $iNumPage);

		if ((!isset($_REQUEST["mode"]) || $_REQUEST["mode"] != "excel") && !empty(self::$navParams["totalCount"]))
		{
			$this->NavRecordCount = self::$navParams["totalCount"];
			$this->NavPageCount = self::$navParams["totalPages"];
			$this->NavPageNomer = self::$navParams["pagen"];
		}
	}

	public function GetNavPrint($title, $show_allways=true, $StyleText="", $template_path=false, $arDeleteParam=false)
	{
		$componentObject = null;
		$this->bShowAll = false;
		return $this->getPageNavStringEx(
			$componentObject,
			"",
			"grid",
			false,
			null,
			$this->componentParams
		);
	}

	public function GetNavSize($tableId = false, $nPageSize = 20, $listUrl = '')
	{
		$tableId = $tableId ? $tableId : $this->table_id;
		$gridOptions = new Bitrix\Main\Grid\Options($tableId);
		$navParams = $gridOptions->getNavParams();
		return $navParams["nPageSize"];
	}

	public function setNavigationParams(array $params)
	{
		$gridOptions = new Bitrix\Main\Grid\Options($this->table_id);
		$this->componentParams = array_merge($params, $gridOptions->getNavParams());
	}
}

class CAdminUiContextMenu extends CAdminContextMenu
{
	private $isShownFilterContext = false;

	public function setFilterContextParam($bool)
	{
		$this->isShownFilterContext = $bool;
	}

	public function Show()
	{
		foreach (GetModuleEvents("main", "OnAdminContextMenuShow", true) as $arEvent)
		{
			ExecuteModuleEventEx($arEvent, array(&$this->items, &$this->additional_items));
		}

		if (empty($this->items) && empty($this->additional_items))
		{
			return;
		}

		\Bitrix\Main\UI\Extension::load(["ui.buttons", "ui.buttons.icons"]);

		if ($this->isPublicMode): ob_start(); ?>
		<div class="pagetitle-container pagetitle-align-right-container">
		<? else: ?>
		<? if (!$this->isShownFilterContext): ?>
			<div class="adm-toolbar-panel-container">
				<div class="adm-toolbar-panel-flexible-space">
					<? $this->showBaseButton(); ?>
				</div>
		<? endif ?>
		<div class="adm-toolbar-panel-align-right">
		<? endif;

		$this->showActionButton();

		if ($this->isShownFilterContext || $this->isPublicMode)
		{
			$this->showBaseButton();
		}

		?>
		</div>
		<? if (!$this->isShownFilterContext && !$this->isPublicMode): ?>
		</div>
		<? endif;

		if ($this->isPublicMode)
		{
			global $APPLICATION;
			$APPLICATION->AddViewContent("inside_pagetitle", ob_get_clean());
		}
	}

	private function showActionButton()
	{
		if (!empty($this->additional_items))
		{
			if ($this->isPublicMode)
			{
				$menuUrl = "BX.adminList.showPublicMenu(this, ".HtmlFilter::encode(
					CAdminPopup::PhpToJavaScript($this->additional_items)).");";
			}
			else
			{
				$menuUrl = "BX.adminList.ShowMenu(this, ".HtmlFilter::encode(
					CAdminPopup::PhpToJavaScript($this->additional_items)).");";
			}

			?>
			<button class="ui-btn ui-btn-light-border ui-btn-themes ui-btn-icon-setting" onclick="
				<?=$menuUrl?>"></button>
			<?
		}
	}

	private function showBaseButton()
	{
		if (!empty($this->items))
		{
			$items = $this->items;
			$firstItem = array_shift($items);
			if (!empty($firstItem["MENU"]))
			{
				$items = array_merge($items, $firstItem["MENU"]);
			}
			if ($this->isPublicMode)
			{
				$menuUrl = "BX.adminList.showPublicMenu(this, ".HtmlFilter::encode(
					CAdminPopup::PhpToJavaScript($items)).");";
			}
			else
			{
				$menuUrl = "BX.adminList.ShowMenu(this, ".HtmlFilter::encode(
					CAdminPopup::PhpToJavaScript($items)).");";
			}
			if (!empty($items)):?>
				<? if (!empty($firstItem["ONCLICK"])): ?>
					<div class="ui-btn-split ui-btn-primary">
						<button onclick="<?=HtmlFilter::encode($firstItem["ONCLICK"])?>" class="ui-btn-main">
							<?=HtmlFilter::encode($firstItem["TEXT"])?>
						</button>
						<button onclick="<?=$menuUrl?>" class="ui-btn-extra"></button>
					</div>
				<? else: ?>
					<? if (isset($firstItem["DISABLE"])): ?>
						<div class="ui-btn-split ui-btn-primary">
							<button onclick="<?=$menuUrl?>" class="ui-btn-main">
								<?=HtmlFilter::encode($firstItem["TEXT"])?>
							</button>
							<button onclick="<?=$menuUrl?>" class="ui-btn-extra"></button>
						</div>
					<? else: ?>
						<div class="ui-btn-split ui-btn-primary">
							<a href="<?=HtmlFilter::encode($firstItem["LINK"])?>" class="ui-btn-main">
								<?=HtmlFilter::encode($firstItem["TEXT"])?>
							</a>
							<button onclick="<?=$menuUrl?>" class="ui-btn-extra"></button>
						</div>
					<? endif; ?>
				<? endif; ?>
			<? else:?>
				<? if (!empty($firstItem["ONCLICK"])): ?>
					<button class="ui-btn ui-btn-primary" onclick="<?=HtmlFilter::encode($firstItem["ONCLICK"])?>">
						<?=HtmlFilter::encode($firstItem["TEXT"])?>
					</button>
				<? else: ?>
					<a class="ui-btn ui-btn-primary" href="<?=HtmlFilter::encode($firstItem["LINK"])?>">
						<?=HtmlFilter::encode($firstItem["TEXT"])?>
					</a>
				<? endif; ?>
			<?endif;
		}
	}
}

class CAdminUiSorting extends CAdminSorting
{
	/**
	 * @return array
	 */
	protected function getUserSorting()
	{
		$result = [
			'by' => null,
			'order' => null
		];
		$gridOptions = new Grid\Options($this->table_id);
		$sorting = $gridOptions->getSorting();
		if (!empty($sorting['sort']))
		{
			$order = reset($sorting['sort']);
			$result['by'] = key($sorting['sort']);
			$result['order'] = strtoupper($order) === 'ASC' ? 'ASC' : 'DESC';
		}

		return $result;
	}
}admin_filter.php000066400000055435147732346240007744 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

class CAdminFilter
{
	public 	$id;
	private $popup;
	private $arItems = array();
	private $arOptFlt = array();
	private static $defaultSort = 100;
	private static $defaultPresetSort = 50;
	private $url=false;
	private $tableId=false;

	const SESS_PARAMS_NAME = "main.adminFilter";

	public function __construct($id, $popup=false, $arExtraParams=array())
	{
		global $USER;

		$uid = $USER->GetID();
		$isAdmin = $USER->CanDoOperation('edit_other_settings');

		if(empty($popup) || !is_array($popup))
			$popup = false;

		$this->id = $id;
		$this->popup = $popup;

		if(is_array($arExtraParams))
		{
			if(isset($arExtraParams["url"]) && !empty($arExtraParams["url"]))
				$this->url = $arExtraParams["url"];

			if(isset($arExtraParams["table_id"]) && !empty($arExtraParams["table_id"]))
				$this->tableId = $arExtraParams["table_id"];
		}

		$this->arOptFlt = CUserOptions::GetOption("filter", $this->id, array(
			"rows" => "",
			"styleFolded" => "N",
			"presetsDeleted" => ""
		));

		$presetsDeleted = explode(",", $this->arOptFlt["presetsDeleted"]);

		$this->arOptFlt["presetsDeleted"] = $presetsDeleted ? $presetsDeleted : array();

		$presetsDeletedJS='';

		if(is_array($presetsDeleted))
			foreach($presetsDeleted as $preset)
				if(trim($preset) <> "")
					$presetsDeletedJS .= ($presetsDeletedJS <> "" ? ",":"").'"'.CUtil::JSEscape(trim($preset)).'"';

		$this->arOptFlt["presetsDeletedJS"] = $presetsDeletedJS;

		$dbRes = self::GetList(array(), array("USER_ID" => $uid, "FILTER_ID" => $this->id), true);
		while($arFilter = $dbRes->Fetch())
		{
			if(!is_null($arFilter["LANGUAGE_ID"]) && $arFilter["LANGUAGE_ID"] != LANG )
				continue;

			$arItem = $arFilter;
			$arItem["FIELDS"] = unserialize($arFilter["FIELDS"]);

			if(!is_null($arFilter["SORT_FIELD"]))
				$arItem["SORT_FIELD"] = unserialize($arFilter["SORT_FIELD"]);

			if($arFilter["PRESET"] == "Y" && is_null($arFilter["LANGUAGE_ID"]))
			{
				$langName = GetMessage($arFilter["NAME"]);

				if($langName)
						$arItem["NAME"] = $langName;

				foreach ($arItem["FIELDS"] as $key => $field)
				{
					$langValue = GetMessage($arItem["FIELDS"][$key]["value"]);

					if($langValue)
						$arItem["FIELDS"][$key]["value"] = $langValue;
				}
			}

			$arItem["EDITABLE"] = ((($isAdmin || $arFilter["USER_ID"] == $uid ) && $arFilter["PRESET"] != "Y") ? true : false );

			$this->AddItem($arItem);
		}
	}

	private function err_mess()
	{
		return "<br>Class: CAdminFilter<br>File: ".__FILE__;
	}

	private function AddItem($arItem, $bInsertFirst = false)
	{
		//if user "deleted" preset http://jabber.bx/view.php?id=34405
		if(!$arItem["EDITABLE"] && !empty($this->arOptFlt["presetsDeleted"]))
			if(in_array($arItem["ID"], $this->arOptFlt["presetsDeleted"]))
				return false;

		$customPresetId = $this->FindItemByPresetId($arItem["ID"]);

		if($customPresetId)
		{
			$this->arItems[$customPresetId]["SORT"] = $arItem["SORT"];
			return false;
		}

		if(isset($arItem["PRESET_ID"]))
		{
			$presetID = $this->FindItemByID($arItem["PRESET_ID"]);

			if($presetID)
			{
				$arItem["SORT"] = $this->arItems[$presetID]["SORT"];
				unset($this->arItems[$presetID]);
			}

		}

		if(!isset($arItem["SORT"]))
			$arItem["SORT"] = self::$defaultSort;

		if($bInsertFirst)
		{
			$arNewItems[$arItem["ID"]] = $arItem;

			foreach ($this->arItems as $key => $item)
				$arNewItems[$key] = $item;

			$this->arItems = $arNewItems;
		}
		else
			$this->arItems[$arItem["ID"]] = $arItem;

		unset($this->arItems[$arItem["ID"]][$arItem["ID"]]);

		return true;
	}

	private function CheckFields($arFields)
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$aMsg = array();

		if(!is_set($arFields, "FILTER_ID") || (is_set($arFields, "FILTER_ID") && trim($arFields["FILTER_ID"])==""))
			$aMsg[] = array("id"=>"FILTER_ID", "text"=>GetMessage("filters_error_table_name"));

		if(!is_set($arFields, "NAME") || (is_set($arFields, "NAME") && trim($arFields["NAME"])==""))
			$aMsg[] = array("id"=>"NAME", "text"=>GetMessage("filters_error_name"));

		if(!is_set($arFields, "FIELDS") || (is_set($arFields, "FIELDS") && trim($arFields["FIELDS"])==""))
			$aMsg[] = array("id"=>"FIELDS", "text"=>GetMessage("filters_error_fields"));

		if((!is_set($arFields, "USER_ID") && $arFields["COMMON"] != "Y") || (is_set($arFields, "USER_ID") && trim($arFields["USER_ID"])==""))
			$aMsg[] = array("id"=>"USER_ID", "text"=>GetMessage("filters_error_user"));

		if(is_set($arFields, "USER_ID"))
		{
			if(intval($arFields["USER_ID"]) > 0)
			{
				$res = CUser::GetByID(intval($arFields["USER_ID"]));
				if(!$res->Fetch())
					$aMsg[] = array("id"=>"USER_ID", "text"=>GetMessage("filters_error_user"));
			}
		}

		if(!empty($aMsg))
		{
			$e = new CAdminException($aMsg);
			$APPLICATION->ThrowException($e);
			return false;
		}

		return true;
	}

	private function FieldsExcess($arFields)
	{
		$arResult = array();

		if(is_array($arFields))
			foreach ($arFields as $key => $field)
					$arResult[$key] = array(
										"value" => $field,
										"hidden" => "false",
										);
		return $arResult;
	}

	private function FieldsDelHiddenEmpty($arFields)
	{
		$arResult = array();

		if(!is_array($arFields))
			return false;

		foreach ($arFields as $key => $field)
		{
				if(!empty($field["value"]) || $field["hidden"] == "false")
					$arResult[$key] = array(
										"value" => $field["value"],
										"hidden" => $field["hidden"],
										);
		}
		return $arResult;
	}

	/**
	 * Sets default rows, witch will be shown to user when he comes to page for the first time/
	 * This function must be called on admin page with the filter initialization.
	 * For example: $oFilter->SetDefaultRows("find_created, find_menu_id");
	 *
	 * @param str rows - rows identificators separated by commas ("rowid_1, rowid_2, ...")
	 * @return bool
	 */
	public function SetDefaultRows($rows)
	{
		if(is_array($rows))
			$outRows = implode(",",$rows);
		else
			$outRows = $rows;

		if(!$outRows)
			return false;

		if(!empty($this->arOptFlt["rows"]))
			return true;

		$this->arOptFlt["rows"] = $outRows;

		return true;
	}

	public static function SetDefaultRowsOption($filterId, $rows)
	{
		if(!$filterId)
			return false;

		if(is_array($rows))
			$outRows = implode(",",$rows);
		else
			$outRows = $rows;

		if(!$outRows)
			return false;

		return CUserOptions::SetOption("filter", $filterId, array("rows" => $outRows),true);
	}

	/**
	 * Sets new filter tab with collection of fields and values
	 * This function must be called on admin page with the filter initialization.
	 * For example: $oFilter->AddPreset(array(
	 *									"ID" => "preset1",
	 *									"NAME" => "Test filter",
	 *									"SORT" => 100,
	 *									"SORT_FIELD" => array ("name" => "asc"),
	 *									"FIELDS" => array(
	 *										"find_name"=>"Smith",
	 *										"find_id"=>"15"
	 *										)
	 *									));
	 *
	 * @param array $arFields = array(
	 *								"ID" =>  filter id,
	 *								"NAME" => filter name,
	 *								"SORT" = > filter sorting order. Default value - 100, for presets - 50;
	 *								"SORT_FIELD" => array("Table column name" => "sort order"),
	 *								"FIELDS" => array(
	 *											"field1_name" => "field1_value",
	 *											"field2_name" => "field2_value",
	 *											...
	 * 												)
	 *							)
	 * @return bool
	 */
	public function AddPreset($arFields)
	{
		if(!isset($arFields["NAME"]) || empty($arFields["NAME"]))
			return false;

		if(!isset($arFields["ID"]) || empty($arFields["ID"]))
			return false;

		$item = array(
			"ID" => "page-".$arFields["ID"],
			"FILTER_ID" => $this->id,
			"NAME" => $arFields["NAME"],
			"EDITABLE" => false,
			"PRESET" => "Y"
			);

		if(isset($arFields["FIELDS"]))
			$item["FIELDS"] = CAdminFilter::FieldsExcess($arFields["FIELDS"]);
		else
			$item["FIELDS"] = array();

		if(isset($arFields["SORT"]) && !empty($arFields["SORT"]))
			$item["SORT"] = intval($arFields["SORT"]);
		else
			$item["SORT"] =self::$defaultPresetSort+count($this->arItems)*10;

		if(isset($arFields["SORT_FIELD"]) && is_array($arFields["SORT_FIELD"]) && !empty($arFields["SORT_FIELD"]))
			$item["SORT_FIELD"] = $arFields["SORT_FIELD"];

		return $this->AddItem($item, false);
	}


	private function FindItemByPresetId($strID)
	{

		if(!is_array($this->arItems))
			return false;

		foreach ($this->arItems as $key => $item)
			if($item["PRESET_ID"] == $strID)
				return $key;

		return false;
	}

	private function FindItemByID($strID)
	{
		if(!is_array($this->arItems))
			return false;

		foreach ($this->arItems as $key => $item)
			if($item["ID"] == $strID)
				return $key;

		return false;
	}

	public function AddPresetToBase($arFields)
	{
		if(!isset($arFields["NAME"]) || empty($arFields["NAME"]))
			return false;

		$arFields["PRESET"] = "Y";
		$arFields["COMMON"] = "Y";

		if(isset($arFields["FIELDS"]))
			$arFields["FIELDS"] = CAdminFilter::FieldsExcess($arFields["FIELDS"]);
		else
			$item["FIELDS"] = array();


		if(!isset($arFields["SORT"]) || empty($arFields["SORT"]))
			$arFields["SORT"] = self::$defaultPresetSort;

		return CAdminFilter::Add($arFields);
	}

	public static function Add($arFields)
	{
		global $DB;

		$arFields["FIELDS"] = CAdminFilter::FieldsDelHiddenEmpty($arFields["FIELDS"]);

		if(!$arFields["FIELDS"])
			return false;

		$arFields["FIELDS"] = serialize($arFields["FIELDS"]);

		if(isset($arFields["SORT_FIELD"]))
			$arFields["SORT_FIELD"] = serialize($arFields["SORT_FIELD"]);

		if(!CAdminFilter::CheckFields($arFields))
			return false;

		$ID = $DB->Add("b_filters", $arFields, array("FIELDS"));
		return $ID;
	}

	public static function Delete($ID)
	{
		global $DB;

		return ($DB->Query("DELETE FROM b_filters WHERE ID='".intval($ID)."'", false, "File: ".__FILE__."<br>Line: ".__LINE__));
	}

	public static function Update($ID, $arFields)
	{
		global $DB;
		$ID = intval($ID);

		$arFields["FIELDS"] = CAdminFilter::FieldsDelHiddenEmpty($arFields["FIELDS"]);

		if(!$arFields["FIELDS"])
			return false;

		$arFields["FIELDS"] = serialize($arFields["FIELDS"]);

		if(isset($arFields["SORT_FIELD"]))
			$arFields["SORT_FIELD"] = serialize($arFields["SORT_FIELD"]);

		if(!CAdminFilter::CheckFields($arFields))
			return false;

		$strUpdate = $DB->PrepareUpdate("b_filters", $arFields);

		$arBinds=Array();
		if(is_set($arFields, "FIELDS"))
			$arBinds["FIELDS"] = $arFields["FIELDS"];


		if(strlen($strUpdate) > 0)
		{
			$strSql = "UPDATE b_filters SET ".$strUpdate." WHERE ID=".$ID;
			return $DB->QueryBind($strSql, $arBinds);

			//if(!$DB->Query($strSql))
			//	return false;
		}

		return false;
	}

	public static function GetList($aSort=array(), $arFilter=Array(), $getCommon=true)
	{
		global $DB;

		$err_mess = (CAdminFilter::err_mess())."<br>Function: GetList<br>Line: ";
		$arSqlSearch = Array();
		if (is_array($arFilter))
		{
			foreach ($arFilter as $key => $val)
			{
				if (strlen($val)<=0 || $val=="NOT_REF")
					continue;

				switch(strtoupper($key))
				{
				case "ID":
					$arSqlSearch[] = GetFilterQuery("F.ID",$val,"N");
					break;
				case "USER_ID":
					if($getCommon)
						$arSqlSearch[] = "F.USER_ID=".intval($val)." OR F.COMMON='Y'";
					else
						$arSqlSearch[] = "F.USER_ID = ".intval($val);
					break;
				case "FILTER_ID":
					$arSqlSearch[] = "F.FILTER_ID = '".$DB->ForSql($val)."'";
					break;
				case "NAME":
					$arSqlSearch[] = GetFilterQuery("F.NAME", $val);
					break;
				case "FIELDS":
					$arSqlSearch[] = GetFilterQuery("F.FIELDS", $val);
					break;
				case "COMMON":
					$arSqlSearch[] = "F.COMMON = '".$DB->ForSql($val,1)."'";
					break;
				case "PRESET":
					$arSqlSearch[] = "F.PRESET = '".$DB->ForSql($val,1)."'";
					break;
				case "LANGUAGE_ID":
					$arSqlSearch[] = "F.LANGUAGE_ID = '".$DB->ForSql($val,2)."'";
					break;
				case "PRESET_ID":
					$arSqlSearch[] = GetFilterQuery("F.PRESET_ID", $val);
					break;
				case "SORT":
					$arSqlSearch[] = GetFilterQuery("F.SORT", $val);
					break;
				case "SORT_FIELD":
					$arSqlSearch[] = GetFilterQuery("F.SORT_FIELD", $val);
					break;
				}
			}
		}

		$sOrder = "";
		foreach($aSort as $key=>$val)
		{
			$ord = (strtoupper($val) <> "ASC"? "DESC":"ASC");
			switch (strtoupper($key))
			{
				case "ID":		$sOrder .= ", F.ID ".$ord; break;
				case "USER_ID":	$sOrder .= ", F.USER_ID ".$ord; break;
				case "FILTER_ID":	$sOrder .= ", F.FILTER_ID ".$ord; break;
				case "NAME":	$sOrder .= ", F.NAME ".$ord; break;
				case "FIELDS":	$sOrder .= ", F.FIELDS ".$ord; break;
				case "COMMON":	$sOrder .= ", F.COMMON ".$ord; break;
				case "PRESET":	$sOrder .= ", F.PRESET ".$ord; break;
				case "LANGUAGE_ID":	$sOrder .= ", F.LANGUAGE_ID ".$ord; break;
				case "PRESET_ID":	$sOrder .= ", F.PRESET_ID ".$ord; break;
				case "SORT":	$sOrder .= ", F.SORT ".$ord; break;
				case "SORT_FIELD":	$sOrder .= ", F.SORT_FIELD ".$ord; break;
			}
		}
		if (strlen($sOrder)<=0)
			$sOrder = "F.ID ASC";
		$strSqlOrder = " ORDER BY ".TrimEx($sOrder,",");

		$strSqlSearch = GetFilterSqlSearch($arSqlSearch,"noFilterLogic");
		$strSql = "
			SELECT
				F.ID, F.USER_ID, F.NAME, F.FILTER_ID, F.FIELDS, F.COMMON, F.PRESET, F.LANGUAGE_ID, F.PRESET_ID, F.SORT, F.SORT_FIELD
			FROM
				b_filters F
			WHERE
			".$strSqlSearch."
			".$strSqlOrder;

		$res = $DB->Query($strSql, false, $err_mess.__LINE__);
		return $res;
	}

	private static function Cmp($a, $b)
	{
		if ($a["SORT"] == $b["SORT"])
			return ($a["ID"] < $b["ID"]) ? -1 : 1;

		return ($a["SORT"] < $b["SORT"]) ? -1 : 1;
	}

	public function Begin()
	{
		uasort($this->arItems, "CAdminFilter::Cmp");

		echo '
<div id="adm-filter-tab-wrap-'.$this->id.'" class="adm-filter-wrap'.($this->arOptFlt["styleFolded"]=="Y" ? " adm-filter-folded" : "").'" style = "display: none;">
	<table class="adm-filter-main-table">
		<tr>
			<td class="adm-filter-main-table-cell">
				<div class="adm-filter-tabs-block" id="filter-tabs-'.$this->id.'">
					<span id="adm-filter-tab-'.$this->id.'-0" class="adm-filter-tab adm-filter-tab-active" onclick="'.$this->id.'.SetActiveTab(this); '.$this->id.'.ApplyFilter(\'0\'); " title="'.GetMessage("admin_lib_filter_goto_dfilter").'">'.GetMessage("admin_lib_filter_filter").'</span>';

		if(is_array($this->arItems) && !empty($this->arItems))
		{
			foreach($this->arItems as $filter_id => $filter)
			{
				$name = ($filter["NAME"] <> '' ? $filter["NAME"] : GetMessage("admin_lib_filter_no_name"));
				echo '<span id="adm-filter-tab-'.$this->id.'-'.$filter_id.'" class="adm-filter-tab" onclick="'.$this->id.'.SetActiveTab(this); '.$this->id.'.ApplyFilter(\''.$filter_id.'\');" title="'.GetMessage("admin_lib_filter_goto_filter").": &quot;".htmlspecialcharsbx($name).'&quot;">'.htmlspecialcharsbx($name).'</span>';
			}
		}

			echo '<span id="adm-filter-add-tab-'.$this->id.'" class="adm-filter-tab adm-filter-add-tab" onclick="'.$this->id.'.SaveAs();" title="'.GetMessage("admin_lib_filter_new").'"></span><span onclick="'.$this->id.'.SetFoldedView();" class="adm-filter-switcher-tab"><span id="adm-filter-switcher-tab" class="adm-filter-switcher-tab-icon"></span></span><span class="adm-filter-tabs-block-underlay"></span>
				</div>
			</td>
		</tr>
		<tr>
			<td class="adm-filter-main-table-cell">
				<div class="adm-filter-content" id="'.$this->id.'_content">
					<div class="adm-filter-content-table-wrap">
						<table cellspacing="0" class="adm-filter-content-table" id="'.$this->id.'">';
	}

	/**
	 * @param bool|array $aParams
	 */
	public function Buttons($aParams=false)
	{
		$hkInst = CHotKeys::getInstance();

		echo '

						</table>
					</div>
					<div class="adm-filter-bottom-separate" id="'.$this->id.'_bottom_separator"></div>
					<div class="adm-filter-bottom">';

		if($aParams !== false)
		{
			$url = $aParams["url"];
			if(strpos($url, "?")===false)
				$url .= "?";
			else
				$url .= "&";

			if(strpos($url, "lang=")===false)
				$url .= "lang=".LANG;

			if(!$this->url)
				$this->url = $url;

			if(!$this->tableId)
				$this->tableId = $aParams["table_id"];

			if(isset($aParams['report']) && $aParams['report'])
			{
				echo '
						<input type="submit" class="adm-btn" id="'.$this->id.'set_filter" name="set_filter" title="'.GetMessage("admin_lib_filter_set_rep_title").$hkInst->GetTitle("set_filter").'" onclick="return '.htmlspecialcharsbx($this->id.'.OnSet(\''.CUtil::AddSlashes($aParams["table_id"]).'\', \''.CUtil::AddSlashes($url).'\', this);').'" value="'.GetMessage("admin_lib_filter_set_rep").'">
						<input type="submit" class="adm-btn" id="'.$this->id.'del_filter" name="del_filter" title="'.GetMessage("admin_lib_filter_clear_butt_title").$hkInst->GetTitle("del_filter").'" onclick="return '.htmlspecialcharsbx($this->id.'.OnClear(\''.CUtil::AddSlashes($aParams["table_id"]).'\', \''.CUtil::AddSlashes($url).'\', this);').'" value="'.GetMessage("admin_lib_filter_clear_butt").'">';
			}
			else
				echo '
						<input type="submit" class="adm-btn" id="'.$this->id.'set_filter" name="set_filter" title="'.GetMessage("admin_lib_filter_set_butt").$hkInst->GetTitle("set_filter").'" onclick="return '.htmlspecialcharsbx($this->id.'.OnSet(\''.CUtil::AddSlashes($aParams["table_id"]).'\', \''.CUtil::AddSlashes($url).'\', this);').'" value="'.GetMessage("admin_lib_filter_set_butt").'">
						<input type="submit" class="adm-btn" id="'.$this->id.'del_filter" name="del_filter" title="'.GetMessage("admin_lib_filter_clear_butt").$hkInst->GetTitle("del_filter").'" onclick="return '.htmlspecialcharsbx($this->id.'.OnClear(\''.CUtil::AddSlashes($aParams["table_id"]).'\', \''.CUtil::AddSlashes($url).'\', this);').'" value="'.GetMessage("admin_lib_filter_clear_butt").'">';

		}
		if($this->popup)
		{

			echo '
						<div class="adm-filter-setting-block">
							<span class="adm-filter-setting" onClick="this.blur();'.$this->id.'.SaveMenuShow(this);return false;" hidefocus="true" title="'.GetMessage("admin_lib_filter_savedel_title").'"></span>
							<span class="adm-filter-add-button" onClick="this.blur();'.$this->id.'.SettMenuShow(this);return false;" hidefocus="true" title="'.GetMessage("admin_lib_filter_more_title").'"></span>
						</div>';
		}
	}

	public function End()
	{

		echo '
					</div>
				</div>
			</td>
		</tr>
	</table>
</div>';

		$sRowIds = $sVisRowsIds = "";


		if(is_array($this->popup))
		{
			foreach($this->popup as $key=>$item)
				if($item !== null)
					$sRowIds .= ($sRowIds <> ""? ",":"").'"'.CUtil::JSEscape($key).'"';

			$aRows = explode(",", $this->arOptFlt["rows"]);

			if(is_array($aRows))
				foreach($aRows as $row)
					if(trim($row) <> "")
						$sVisRowsIds .= ($sVisRowsIds <> ""? ",":"").'"'.CUtil::JSEscape(trim($row)).'":true';
		}

		$this->PrintSaveOptionsDIV();
		$this->GetParamsFromCookie();

		$openedTabUri = false;
		$openedTabSes = $filteredTab = null;

		if(isset($_REQUEST["adm_filter_applied"]) && !empty($_REQUEST["adm_filter_applied"]))
		{
			$openedTabUri = $_REQUEST["adm_filter_applied"];
		}
		else
		{
			$openedTabSes = $_SESSION[self::SESS_PARAMS_NAME][$this->id]["activeTabId"];
			$filteredTab = $_SESSION[self::SESS_PARAMS_NAME][$this->id]["filteredId"];
		}

		echo '
<script type="text/javascript">
	var '.$this->id.' = {};
	BX.ready(function(){
		'.$this->id.' = new BX.AdminFilter("'.$this->id.'", ['.$sRowIds.']);
		if (!BX.adminMenu)
		{
			BX.adminMenu = new BX.adminMenu();
		}
		'.$this->id.'.state.init = true;
		'.$this->id.'.state.folded = '.($this->arOptFlt["styleFolded"] == "Y" ? "true" : "false").';
		'.$this->id.'.InitFilter({'.$sVisRowsIds.'});
		'.$this->id.'.oOptions = '.CUtil::PhpToJsObject($this->arItems).';
		'.$this->id.'.popupItems = '.CUtil::PhpToJsObject($this->popup).';
		'.$this->id.'.InitFirst();
		'.$this->id.'.url = "'.CUtil::JSEscape($this->url).'";
		'.$this->id.'.table_id = "'.CUtil::JSEscape($this->tableId).'";
		'.$this->id.'.presetsDeleted = ['.$this->arOptFlt["presetsDeletedJS"].'];';

		if($filteredTab != null || $openedTabUri != false)
		{
			$tabToInit = ($openedTabUri ? $openedTabUri : $filteredTab);

			echo '
		'.$this->id.'.InitFilteredTab("'.CUtil::JSEscape($tabToInit).'");';
		}

		if($openedTabSes != null || $openedTabUri != false)
			echo '
		var openedFTab = '.$this->id.'.InitOpenedTab("'.CUtil::JSEscape($openedTabUri).'", "'.CUtil::JSEscape($openedTabSes).'");';

		echo '
		'.$this->id.'.state.init = false;
		BX("adm-filter-tab-wrap-'.$this->id.'").style.display = "block";';

		//making filter tabs draggable
		if($this->url)
		{
			$registerUrl = CHTTP::urlDeleteParams($this->url, array("adm_filter_applied", "adm_filter_preset"));

			foreach($this->arItems as $filter_id => $filter)
			{
				$arParamsAdd = array("adm_filter_applied"=>$filter_id);

				if(isset($filter["PRESET_ID"]))
					$arParamsAdd["adm_filter_preset"] = $filter["PRESET_ID"];

				$filterUrl = CHTTP::urlAddParams($registerUrl, $arParamsAdd, array("encode","skip_empty"));

				echo "
		BX.adminMenu.registerItem('adm-filter-tab-".$this->id.'-'.$filter_id."', {URL:'".$filterUrl."', TITLE: true});";
			}
		}

		echo '
	});
</script>';

		$hkInst = CHotKeys::getInstance();
		$Execs = $hkInst->GetCodeByClassName("CAdminFilter");
		echo $hkInst->PrintJSExecs($Execs);
	}


	//experemental
	//extracting filter params from cookie and transfer them to session
	private function GetParamsFromCookie()
	{
		$cookieName = COption::GetOptionString("main", "cookie_name", "BITRIX_SM")."_ADM_FLT_PARAMS";
		if(!isset($_COOKIE[$cookieName]) || $_COOKIE[$cookieName] == "")
			return false;

		$aParams = explode(",",$_COOKIE[$cookieName]);
		SetCookie($cookieName,'');

		if(empty($aParams))
			return false;

		$filterId = "";

		foreach ($aParams as $key => $aValue)
		{
			$aParam = explode(":",$aValue);
			unset($aParams[$key]);

			if(!empty($aParam) && $aParam[0] != "filter_id")
				$aParams[$aParam[0]] = $aParam[1];
			elseif($aParam[0] == "filter_id")
				$filterId = $aParam[1];
		}

		if($filterId == "")
			return false;

		foreach ($aParams as $paramName => $value)
			$_SESSION[self::SESS_PARAMS_NAME][$filterId][$paramName] = $value;

		return true;
	}

	//experemental
	private function IsFiltered()
	{
		$fltTable = $_SESSION["SESS_ADMIN"][$this->tableId];

		if(!isset($fltTable) || !is_array($fltTable))
			return false;

		foreach ($fltTable as $value)
			if(!is_null($value))
				return true;

		return false;
	}

	private function PrintSaveOptionsDIV()
	{
		global $USER;
		$isAdmin = $USER->CanDoOperation('edit_other_settings');
		?>
<div style="display:none">
	<div id="filter_save_opts_<?=$this->id?>">
		<table width="100%">
			<tr>
				<td align="right" width="40%"><?=GetMessage("admin_lib_filter_sett_name")?></td>
				<td><input type="text" name="save_filter_name" value="" size="30" maxlength="255"></td>
			</tr>
			<?if($isAdmin):?>
				<tr>
					<td align="right" width="40%"><?=GetMessage("admin_lib_filter_sett_common")?></td>
					<td><input type="checkbox" name="common" ></td>
				</tr>
			<?endif;?>
		</table>
	</div>
</div>
		<?
	}

	public static function UnEscape($aFilter)
	{
		if(defined("BX_UTF"))
			return;
		if(!is_array($aFilter))
			return;
		foreach($aFilter as $flt)
			if(is_string($GLOBALS[$flt]) && CUtil::DetectUTF8($GLOBALS[$flt]))
				CUtil::decodeURIComponent($GLOBALS[$flt]);
	}
}
admin_tabcontrol.php000064400000041007147732346240010612 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

/*Tab Control*/
class CAdminTabControl
{
	var $name, $unique_name;
	var $tabs = array();
	var $selectedTab;
	var $tabIndex = 0;
	var $bButtons = false;
	var $arButtonsParams = false;
	var $bCanExpand;
	var $bPublicModeBuffer = false;
	var $bShowSettings = false;
	var $publicModeBuffer_id;

	/** @var CAdminTabEngine */
	var $customTabber;

	var $bPublicMode = false;
	var $isPublicFrame = false;
	var $publicObject = 'BX.WindowManager.Get()';

	var $AUTOSAVE = null;
	protected $tabEvent = false;

	var $isSidePanel = false;
	var $publicSidePanel = false;
	var $isShownSidePanelFields = false;

	public function __construct($name, $tabs, $bCanExpand = true, $bDenyAutoSave = false)
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		//array(array("DIV"=>"", "TAB"=>"", "ICON"=>, "TITLE"=>"", "ONSELECT"=>"javascript"), ...)
		if(is_array($tabs))
		{
			$this->tabs = $tabs;
		}
		$this->name = $name;
		$this->unique_name = $name."_".md5($APPLICATION->GetCurPage());

		global $adminSidePanelHelper;
		$this->publicSidePanel =  (is_object($adminSidePanelHelper) && $adminSidePanelHelper->isPublicSidePanel());
		$this->bPublicMode = defined('BX_PUBLIC_MODE') && BX_PUBLIC_MODE == 1;
		$this->bCanExpand = !$this->bPublicMode && (bool)$bCanExpand;

		$this->SetSelectedTab();

		if (!$bDenyAutoSave && CAutoSave::Allowed())
		{
			$this->AUTOSAVE = new CAutoSave();
		}

		$this->isSidePanel = ((isset($_REQUEST["IFRAME"]) && $_REQUEST["IFRAME"] === "Y") &&
			isset($_REQUEST["IFRAME_TYPE"]) && $_REQUEST["IFRAME_TYPE"] === "SIDE_SLIDER");
		$this->isPublicFrame = $this->isSidePanel && (isset($_REQUEST["IFRAME_TYPE"]) &&
			$_REQUEST["IFRAME_TYPE"] === "PUBLIC_FRAME");
	}

	function SetPublicMode($jsObject = false)
	{
		$this->bPublicMode = true;
		$this->bShowSettings = false;
		$this->bCanExpand = false;
		$this->bPublicModeBuffer = true;

		if ($jsObject)
			$this->publicObject = $jsObject;
	}

	/**
	 * @param CAdminTabEngine $customTabber
	 */
	function AddTabs(&$customTabber)
	{
		if (!$this->customTabber)
		{
			$this->customTabber = $customTabber;

			$arCustomTabs = $this->customTabber->GetTabs();
			if ($arCustomTabs && is_array($arCustomTabs))
			{
				$arTabs = array();
				$i = 0;
				foreach ($this->tabs as $value)
				{
					foreach ($arCustomTabs as $key1 => $value1)
					{
						if (array_key_exists("SORT", $value1) && IntVal($value1["SORT"]) == $i)
						{
							$arTabs[] = array_merge($value1, array("CUSTOM" => "Y"));
							unset($arCustomTabs[$key1]);
						}
					}

					$arTabs[] = $value;
					$i++;
				}

				foreach ($arCustomTabs as $value1)
					$arTabs[] = array_merge($value1, array("CUSTOM" => "Y"));

				$this->tabs = $arTabs;
				$this->SetSelectedTab();
			}
		}
	}

	function OnAdminTabControlBegin()
	{
		if (!$this->tabEvent)
		{
			foreach(GetModuleEvents("main", "OnAdminTabControlBegin", true) as $arEvent)
				ExecuteModuleEventEx($arEvent, array(&$this));
			$this->tabEvent = true;
		}
	}

	function SetSelectedTab()
	{
		$this->selectedTab = $this->tabs[0]["DIV"];
		if(isset($_REQUEST[$this->name."_active_tab"]))
		{
			foreach($this->tabs as $tab)
			{
				if($tab["DIV"] == $_REQUEST[$this->name."_active_tab"])
				{
					$this->selectedTab = $_REQUEST[$this->name."_active_tab"];
					break;
				}
			}
		}
	}

	function Begin()
	{
		$hkInst = CHotKeys::getInstance();

		$this->OnAdminTabControlBegin();
		$this->tabIndex = 0;

		$this->SetSelectedTab();

		if (!$this->bPublicMode)
		{
?>
<div class="adm-detail-block" id="<?=$this->name?>_layout">
	<div class="adm-detail-tabs-block<?=$this->bShowSettings?' adm-detail-tabs-block-settings':''?>" id="<?=$this->name?>_tabs">
<?
		}

		$len = count($this->tabs);
		$tabs_html = '';
		foreach($this->tabs as $key => $tab)
		{
			$bSelected = ($tab["DIV"] == $this->selectedTab);
			$tabs_html .= '<span title="'.$tab["TITLE"].$hkInst->GetTitle("tab-container").'" '.
				'id="tab_cont_'.$tab["DIV"].'" '.
				'class="adm-detail-tab'.($bSelected ? ' adm-detail-tab-active':'').($key==$len-1? ' adm-detail-tab-last':'').'" '.
				'onclick="'.$this->name.'.SelectTab(\''.$tab["DIV"].'\');">'.htmlspecialcharsex($tab["TAB"]).'</span>';
		}

		$tabs_html .= $this->ShowTabButtons();

		if (!$this->bPublicMode)
		{
			echo $tabs_html;
?>
	</div>
	<div class="adm-detail-content-wrap">
<?
		}
		else
		{
			echo '
<script type="text/javascript">
'.$this->publicObject.'.SetHead(\''.CUtil::JSEscape($tabs_html).'\');
';
			if ($this->AUTOSAVE)
			{
				echo '
'.$this->publicObject.'.setAutosave();
';
			}
			echo '
</script>
';
			if ($this->bPublicModeBuffer)
			{
				$this->publicModeBuffer_id = 'bx_tab_control_'.RandString(6);
				echo '<div id="'.$this->publicModeBuffer_id.'" style="display: none;">';
			}
		}
	}

	function ShowTabButtons()
	{
		$s = '';
		if (!$this->bPublicMode)
		{
			if(count($this->tabs) > 1 && $this->bCanExpand/* || $this->AUTOSAVE*/)
			{
				$s .= '<div class="adm-detail-title-setting" onclick="'.$this->name.'.ToggleTabs();" title="'.GetMessage("admin_lib_expand_tabs").'" id="'.$this->name.'_expand_link"><span class="adm-detail-title-setting-btn adm-detail-title-expand"></span></div>';
			}
		}
		return $s;
	}

	function BeginNextTab($options = array())
	{
		if ($this->AUTOSAVE)
			$this->AUTOSAVE->Init();

		//end previous tab
		$this->EndTab();

		if($this->tabIndex >= count($this->tabs))
			return;

		$css = '';
		if ($this->tabs[$this->tabIndex]["DIV"] <> $this->selectedTab)
			$css .= 'display:none; ';

		echo '<div class="adm-detail-content'.(isset($options["className"]) ? " ".$options["className"] : "").'"
		 		id="'.$this->tabs[$this->tabIndex]["DIV"].'"'.($css != '' ? ' style="'.$css.'"' : '').'>';

		/*if($this->tabs[$this->tabIndex]["ICON"] <> "")
			echo '
		<td class="icon"><div id="'.$this->tabs[$this->tabIndex]["ICON"].'"></div></td>
		';*/

		if (!isset($options["showTitle"]) || $options["showTitle"] === true)
		{
			echo '<div class="adm-detail-title">'.$this->tabs[$this->tabIndex]["TITLE"].'</div>';
		}

echo '
	<div class="adm-detail-content-item-block">
		<table class="adm-detail-content-table edit-table" id="'.$this->tabs[$this->tabIndex]["DIV"].'_edit_table">
			<tbody>
';
		if(array_key_exists("CUSTOM", $this->tabs[$this->tabIndex]) && $this->tabs[$this->tabIndex]["CUSTOM"] == "Y")
		{
			$this->customTabber->ShowTab($this->tabs[$this->tabIndex]["DIV"]);
			$this->tabIndex++;
			$this->BeginNextTab();
		}
		elseif(array_key_exists("CONTENT", $this->tabs[$this->tabIndex]))
		{
			echo $this->tabs[$this->tabIndex]["CONTENT"];
			$this->tabIndex++;
			$this->BeginNextTab();
		}
		else
		{
			$this->tabIndex++;
		}
	}

	function EndTab()
	{
		if(
			$this->tabIndex < 1
			|| $this->tabIndex > count($this->tabs)
			|| $this->tabs[$this->tabIndex-1]["_closed"] === true
		)
		{
			return;
		}

		echo '
			</tbody>
		</table>
	</div>
</div>
';

		$this->tabs[$this->tabIndex-1]["_closed"] = true;
	}

	/**
	 * @param bool|array $aParams
	 */
	function Buttons($aParams=false)
	{
		$hkInst = CHotKeys::getInstance();

		while($this->tabIndex < count($this->tabs))
			$this->BeginNextTab();

		$this->bButtons = true;
		if($aParams === false)
			$this->arButtonsParams = false;
		else
			$this->arButtonsParams = $aParams;

		//end previous tab
		$this->EndTab();

		if (!$this->bPublicMode)
		{
			echo '<div class="adm-detail-content-btns-wrap" id="'.$this->name.'_buttons_div"><div class="adm-detail-content-btns">';
		}

		if ($_REQUEST['subdialog'])
		{
			echo '<input type="hidden" name="suffix" value="'.substr($GLOBALS['obJSPopup']->suffix, 1).'" />';
			echo '<input type="hidden" name="subdialog" value="Y" />';
		}

		if($aParams !== false)
		{
			$aParams["ajaxMode"] = (isset($aParams["ajaxMode"]) ? $aParams["ajaxMode"] : true);

			if (!$this->isShownSidePanelFields)
			{
				$this->getSidePanelFields();
			}

			if ($this->bPublicMode)
			{
				if (strlen($_REQUEST['from_module']))
				{
					echo '<input type="hidden" name="from_module" value="'.htmlspecialcharsbx($_REQUEST['from_module']).'" />';
				}

				if(is_array($aParams['buttons']))
				{
					echo '
<input type="hidden" name="bxpublic" value="Y" />
<script type="text/javascript">'.$this->publicObject.'.SetButtons('.CUtil::PhpToJsObject($aParams['buttons']).');</script>
';
				}
				else
				{
					echo '
<input type="hidden" name="bxpublic" value="Y" /><input type="hidden" name="save" value="Y" />
<script type="text/javascript">'.$this->publicObject.'.SetButtons(['.$this->publicObject.'.btnSave, '.$this->publicObject.'.btnCancel]);</script>
';
				}
			}
			elseif($this->isSidePanel && $aParams["ajaxMode"])
			{
				$this->getAjaxButtons($aParams);
			}
			else
			{
				if($aParams["btnSave"] !== false)
				{
					echo '<input'.($aParams["disabled"] === true? " disabled":"").' type="submit" name="save" value="'.GetMessage("admin_lib_edit_save").'" title="'.GetMessage("admin_lib_edit_save_title").$hkInst->GetTitle("Edit_Save_Button").'" class="adm-btn-save" />';
					echo $hkInst->PrintJSExecs($hkInst->GetCodeByClassName("Edit_Save_Button"));
				}
				if($aParams["btnApply"] !== false)
				{
					echo '<input'.($aParams["disabled"] === true? " disabled":"").' type="submit" name="apply" value="'.GetMessage("admin_lib_edit_apply").'" title="'.GetMessage("admin_lib_edit_apply_title").$hkInst->GetTitle("Edit_Apply_Button").'" />';
					echo $hkInst->PrintJSExecs($hkInst->GetCodeByClassName("Edit_Apply_Button"));
				}
				if($aParams["btnCancel"] !== false && $aParams["back_url"] <> '' && !preg_match('/(javascript|data)[\s\0-\13]*:/i', $aParams["back_url"]))
				{
					echo '<input type="button" value="'.GetMessage("admin_lib_edit_cancel").'" name="cancel" onClick="top.window.location=\''.htmlspecialcharsbx(CUtil::addslashes($aParams["back_url"])).'\'" title="'.GetMessage("admin_lib_edit_cancel_title").$hkInst->GetTitle("Edit_Cancel_Button").'" />';
					echo $hkInst->PrintJSExecs($hkInst->GetCodeByClassName("Edit_Cancel_Button"));
				}
				if($aParams["btnSaveAndAdd"] === true)
				{
					echo '<input'.($aParams["disabled"] === true? " disabled":"").' type="submit" name="save_and_add" value="'.GetMessage("admin_lib_edit_save_and_add").'" title="'.GetMessage("admin_lib_edit_save_and_add_title").$hkInst->GetTitle("Edit_Save_And_Add_Button").'" class="adm-btn-add" />';
					echo $hkInst->PrintJSExecs($hkInst->GetCodeByClassName("Edit_Save_And_Add_Button"));
				}
			}
		}
	}

	protected function getAjaxButtons(array $params)
	{
		$htmlAjaxButtons = "";

		if ($params["btnSave"] !== false)
		{
			$htmlAjaxButtons .= '<input type="button" name="save" value="'.GetMessage("admin_lib_edit_save").'" title="'.GetMessage("admin_lib_edit_save_title").'" class="adm-btn-save">';
		}
		if ($params["btnApply"] !== false)
		{
			$htmlAjaxButtons .= '<input type="button" name="apply" value="'.GetMessage("admin_lib_edit_apply").'" title="'.GetMessage("admin_lib_edit_apply_title").'">';
		}
		if ($params["btnCancel"] !== false)
		{
			$htmlAjaxButtons .= '<input type="button" name="cancel" value="'.GetMessage("admin_lib_edit_cancel").'" title="'.GetMessage("admin_lib_edit_cancel_title").'">';
		}
		if ($params["btnSaveAndAdd"] === true)
		{
			global $APPLICATION;
			$addUrl = CHTTP::urlAddParams($APPLICATION->GetCurPage(), array("lang" => LANGUAGE_ID));
			if ($addUrl <> '' && !preg_match('/(javascript|data)[\s\0-\13]*:/i', $addUrl))
			{
				$htmlAjaxButtons .= '<input type="button" name="save_and_add" value="'.GetMessage("admin_lib_edit_save_and_add").'" title="'.GetMessage("admin_lib_edit_save_and_add_title").'" class="adm-btn-add"  data-url="'.htmlspecialcharsbx(CUtil::addslashes($addUrl)).'">';
			}
			else
			{
				$htmlAjaxButtons .= '<input type="button" name="save_and_add" value="'.GetMessage("admin_lib_edit_save_and_add").'" title="'.GetMessage("admin_lib_edit_save_and_add_title").'" class="adm-btn-add">';
			}
		}

		echo $htmlAjaxButtons;
	}

	public function getSidePanelFields()
	{
		if ($this->isSidePanel)
		{
			$this->isShownSidePanelFields = true;

			echo '<input type="hidden" name="IFRAME" value="Y">';
			echo '<input type="hidden" name="IFRAME_TYPE" value="SIDE_SLIDER">';
		}
	}

	/**
	 * @param bool|array $arJSButtons
	 */
	function ButtonsPublic($arJSButtons = false)
	{
		while ($this->tabIndex < count($this->tabs))
			$this->BeginNextTab();

		$this->bButtons = true;
		$this->EndTab();

		if ($this->bPublicMode)
		{
			if (strlen($_REQUEST['from_module']))
				echo '<input type="hidden" name="from_module" value="'.htmlspecialcharsbx($_REQUEST['from_module']).'" />';

			if ($arJSButtons === false)
			{
				echo '
<input type="hidden" name="bxpublic" value="Y" /><input type="hidden" name="save" value="Y" />
<script type="text/javascript">'.$this->publicObject.'.SetButtons(['.$this->publicObject.'.btnSave, '.$this->publicObject.'.btnCancel]);</script>
';
			}
			elseif (is_array($arJSButtons))
			{
				$arJSButtons = array_values($arJSButtons);
				echo '
<input type="hidden" name="bxpublic" value="Y" />
<script type="text/javascript">'.$this->publicObject.'.SetButtons([
';
				foreach ($arJSButtons as $key => $btn)
				{
					if (substr($btn, 0, 1) == '.')
						$btn = $this->publicObject.$btn;
					echo $key ? ',' : '', $btn, "\r\n"; // NO JSESCAPE HERE! string must contain valid js object
				}
				echo '
]);</script>
';
			}
		}
	}

	function End()
	{
		$hkInst = CHotKeys::getInstance();

		if(!$this->bButtons)
		{
			while ($this->tabIndex < count($this->tabs))
				$this->BeginNextTab();

			//end previous tab
			$this->EndTab();
			if (!$this->bPublicMode)
				echo '<div class="adm-detail-content-btns-wrap"><div class="adm-detail-content-btns adm-detail-content-btns-empty"></div></div>';
		}
		elseif (!$this->bPublicMode)
		{
			echo '</div></div>';
		}

		if (!$this->bPublicMode)
		{
			echo '
</div></div>
';
		}

		$Execs = $hkInst->GetCodeByClassName("CAdminTabControl");
		echo $hkInst->PrintJSExecs($Execs, $this->name);

		echo '

<input type="hidden" id="'.$this->name.'_active_tab" name="'.$this->name.'_active_tab" value="'.htmlspecialcharsbx($this->selectedTab).'">

<script type="text/javascript">';
		$s = "";
		foreach($this->tabs as $tab)
		{
			$s .= ($s <> ""? ", ":"").
			"{".
			"'DIV': '".$tab["DIV"]."' ".
			($tab["ONSELECT"] <> ""? ", 'ONSELECT': '".CUtil::JSEscape($tab["ONSELECT"])."'":"").
			"}";
		}
		$adminTabControlParams = array();
		if ($this->arButtonsParams["back_url"] <> '')
			$adminTabControlParams["backUrl"] = $this->arButtonsParams["back_url"];
		if ($this->isPublicFrame)
			$adminTabControlParams["isPublicFrame"] = "Y";
		if ($this->isSidePanel)
			$adminTabControlParams["isSidePanel"] = "Y";
		if ($this->publicSidePanel)
			$adminTabControlParams["publicSidePanel"] = "Y";
		echo '
if (!window.'.$this->name.' || !BX.is_subclass_of(window.'.$this->name.', BX.adminTabControl))
	window.'.$this->name.' = new BX.adminTabControl("'.$this->name.'", "'.$this->unique_name.
			'", ['.$s.'], '.CUtil::phpToJsObject($adminTabControlParams).');
else if(!!window.'.$this->name.')
	window.'.$this->name.'.PreInit(true);
';

		if (!$this->bPublicMode)
		{
			$aEditOpt = CUserOptions::GetOption("edit", $this->unique_name, array());
			$aTabOpt = CUserOptions::GetOption("edit", 'admin_tabs', array());

			if($this->bCanExpand && count($this->tabs) > 1)
			{
				if($aEditOpt["expand"] == "on")
				{
					echo '
'.$this->name.'.ToggleTabs();';
				}
			}

			if ($aTabOpt["fix_top"] == "off" && $aEditOpt["expand"] != "on")
			{
				echo '
'.$this->name.'.ToggleFix(\'top\');';
			}

			if ($aTabOpt["fix_bottom"] == "off")
			{
				echo '
'.$this->name.'.ToggleFix(\'bottom\');';
			}
		}
		else
		{
			echo 'window.'.$this->name.'.setPublicMode(true); ';
		}
echo '
</script>
';
		if ($this->bPublicModeBuffer)
		{
			echo '</div>';
			echo '<script type="text/javascript">BX.ready(function() {'.$this->publicObject.'.SwapContent(\''.$this->publicModeBuffer_id.'\');});</script>';
		}
	}

	function GetSelectedTab()
	{
		return $this->selectedTab;
	}

	function ActiveTabParam()
	{
		return $this->name."_active_tab=".urlencode($this->selectedTab);
	}

	// this method is temporarily disabled!
	//string, CAdminException, array("id"=>"name", ...)
	function ShowWarnings($form, $messages, $aFields=false)
	{
/*
		if(!$messages)
			return;
		$aMess = $messages->GetMessages();
		if(empty($aMess) || !is_array($aMess))
			return;
		$s = "";
		foreach($aMess as $msg)
		{
			$field_name = (is_array($aFields)? $aFields[$msg["id"]] : $msg["id"]);
			if(empty($field_name))
				continue;
			$s .= ($s <> ""? ", ":"")."{'name':'".CUtil::JSEscape($field_name)."', 'title':'".CUtil::JSEscape(htmlspecialcharsback($msg["text"]))."'}";
		}
		echo '
<script>
'.$this->name.'.ShowWarnings("'.CUtil::JSEscape($form).'", ['.$s.']);
</script>
';
*/
	}
}
admin_list.php000066400000122575147732346240007432 0ustar00<?php

use Bitrix\Main\Type\Collection;

/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */
class CAdminList
{
	var $table_id;
	/** @var CAdminSorting */
	var $sort;
	var $aHeaders = array();
	var $aVisibleHeaders = array();
	/** @var CAdminListRow[] */
	var $aRows = array();
	var $aHeader = array();
	var $arVisibleColumns = array();
	var $aFooter = array();
	var $sNavText = '';
	var $arFilterErrors = Array();
	var $arUpdateErrors = array();
	var $arUpdateErrorIDs = Array();
	var $arGroupErrors = array();
	var $arGroupErrorIDs = Array();
	var $arActionSuccess = array();
	var $bEditMode = false;
	var $bMultipart = false;
	var $bCanBeEdited = false;
	var $bCanBeDeleted = false;
	var $arActions = Array();
	var $arActionsParams = Array();
	/** @var CAdminContextMenuList */
	var $context = false;
	var $sContent = false, $sPrologContent = '', $sEpilogContent = '';
	var $bShowActions;
	var $onLoadScript;
	var $arEditedRows;
	var $isPublicMode = false;

	private $filter;

	/**
	 * @param string $table_id
	 * @param CAdminSorting|bool $sort
	 */
	public function __construct($table_id, $sort = false)
	{
		$this->table_id = $table_id;
		$this->sort = $sort;

		$this->isPublicMode = (defined("PUBLIC_MODE") && PUBLIC_MODE == 1);
	}

	/**
	 * @deprecated
	 * @param string $table_id
	 * @param CAdminSorting|bool $sort
	 */
	public function CAdminList($table_id, $sort = false)
	{
		self::__construct($table_id, $sort);
	}

	public function getFilter()
	{
		return $this->filter;
	}

	//id, name, content, sort, default
	public function AddHeaders($aParams)
	{
		if (isset($_REQUEST['showallcol']) && $_REQUEST['showallcol'])
			$_SESSION['SHALL'] = ($_REQUEST['showallcol'] == 'Y');

		$aOptions = CUserOptions::GetOption("list", $this->table_id, array());

		$aColsTmp = explode(",", $aOptions["columns"]);
		$aCols = array();
		$userColumns = array();
		foreach ($aColsTmp as $col)
		{
			$col = trim($col);
			if ($col <> "")
			{
				$aCols[] = $col;
				$userColumns[$col] = true;
			}
		}

		$bEmptyCols = empty($aCols);
		$userVisibleColumns = array();
		foreach ($aParams as $param)
		{
			$param["__sort"] = -1;
			$this->aHeaders[$param["id"]] = $param;
			if (
				(isset($_SESSION['SHALL']) && $_SESSION['SHALL'])
				|| ($bEmptyCols && $param["default"] == true)
				|| isset($userColumns[$param["id"]])
			)
			{
				$this->arVisibleColumns[] = $param["id"];
				$userVisibleColumns[$param["id"]] = true;
			}
		}
		unset($userColumns);

		$aAllCols = null;
		if (isset($_REQUEST["mode"]) && $_REQUEST["mode"] == "settings")
			$aAllCols = $this->aHeaders;

		if (!$bEmptyCols)
		{
			foreach ($aCols as $i => $col)
				if (isset($this->aHeaders[$col]))
					$this->aHeaders[$col]["__sort"] = $i;

			Collection::sortByColumn($this->aHeaders, ['__sort' => SORT_ASC], '', null, true);
		}

		foreach($this->aHeaders as $id=>$arHeader)
		{
			if (isset($userVisibleColumns[$id]))
				$this->aVisibleHeaders[$id] = $arHeader;
		}
		unset($userVisibleColumns);

		if (isset($_REQUEST["mode"]) && $_REQUEST["mode"] == "settings")
			$this->ShowSettings($aAllCols, $aCols, $aOptions);
	}

	function ShowSettings($aAllCols, $aCols, $aOptions)
	{
		global $USER;

		require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_js.php");
		require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/interface/settings_admin_list.php");
		require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin_js.php");
		die();
	}

	public function AddVisibleHeaderColumn($id)
	{
		if (isset($this->aHeaders[$id]) && !isset($this->aVisibleHeaders[$id]))
		{
			$this->arVisibleColumns[] = $id;
			$this->aVisibleHeaders[$id] = $this->aHeaders[$id];
		}
	}

	public function GetVisibleHeaderColumns()
	{
		return $this->arVisibleColumns;
	}

	public function AddAdminContextMenu($aContext=array(), $bShowExcel=true, $bShowSettings=true)
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$aAdditionalMenu = array();

		if($bShowSettings)
		{
			$link = DeleteParam(array("mode"));
			$link = $APPLICATION->GetCurPage()."?mode=settings".($link <> ""? "&".$link:"");
			$aAdditionalMenu[] = array(
				"TEXT"=>GetMessage("admin_lib_context_sett"),
				"TITLE"=>GetMessage("admin_lib_context_sett_title"),
				"ONCLICK"=>$this->table_id.".ShowSettings('".CUtil::JSEscape($link)."')",
				"GLOBAL_ICON"=>"adm-menu-setting",
			);
		}

		if($bShowExcel)
		{
			$link = DeleteParam(array("mode"));
			$link = $APPLICATION->GetCurPage()."?mode=excel".($link <> ""? "&".$link:"");
			$aAdditionalMenu[] = array(
				"TEXT"=>"Excel",
				"TITLE"=>GetMessage("admin_lib_excel"),
				//"LINK"=>htmlspecialcharsbx($link),
				"ONCLICK"=>"location.href='".htmlspecialcharsbx($link)."'",
				"GLOBAL_ICON"=>"adm-menu-excel",
			);
		}

		if(count($aContext)>0 || count($aAdditionalMenu) > 0)
			$this->context = new CAdminContextMenuList($aContext, $aAdditionalMenu);
	}

	/**
	 * @param string|int $ID
	 * @return bool
	 */
	public function IsUpdated($ID)
	{
		$f = $_REQUEST['FIELDS'][$ID];
		$f_old = $_REQUEST['FIELDS_OLD'][$ID];

		if(!is_array($f) || !is_array($f_old))
			return true;

		foreach($f as $k=>$v)
		{
			if(is_array($v))
			{
				if(!is_array($f_old[$k]))
					return true;
				else
				{
					foreach($v as $k2 => $v2)
					{
						if($f_old[$k][$k2] !== $v2)
							return true;
						unset($f_old[$k][$k2]);
					}
					if(count($f_old[$k]) > 0)
						return true;
				}
			}
			else
			{
				if(is_array($f_old[$k]))
					return true;
				elseif($f_old[$k] !== $v)
					return true;
			}
			unset($f_old[$k]);
		}
		if(count($f_old) > 0)
			return true;

		return false;
	}

	/**
	 * @return bool
	 */
	public function EditAction()
	{
		if($_SERVER['REQUEST_METHOD']=='POST' && isset($_REQUEST['save'])  && check_bitrix_sessid())
		{
			$arrays = array(&$_POST, &$_REQUEST, &$GLOBALS);
			foreach($arrays as $i => $array)
			{
				if(is_array($array["FIELDS"]))
				{
					foreach($array["FIELDS"] as $id=>$fields)
					{
						if(is_array($fields))
						{
							$keys = array_keys($fields);
							foreach($keys as $key)
							{
								if(($c = substr($key, 0, 1)) == '~' || $c == '=')
								{
									unset($arrays[$i]["FIELDS"][$id][$key]);
								}
							}
						}
					}
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * Returns field values in for inline edit grid mode.
	 *
	 * @return array
	 */
	public function GetEditFields()
	{
		return (isset($_REQUEST['FIELDS']) && is_array($_REQUEST['FIELDS']) ? $_REQUEST['FIELDS'] : []);
	}

	/**
	 * @return array|false
	 */
	public function GroupAction()
	{
		$this->PrepareAction();

		if (!check_bitrix_sessid())
		{
			return false;
		}

		$action = $this->GetAction();
		if ($action === null)
		{
			return false;
		}

		if($action=="edit")
		{
			$arID = $this->GetGroupIds();
			if ($arID !== null)
			{
				$this->arEditedRows = $arID;
				$this->bEditMode = true;
			}
			return false;
		}

		if (!$this->IsGroupActionToAll())
		{
			$arID = $this->GetGroupIds();
			if ($arID === null)
			{
				$arID = false;
			}
		}
		else
		{
			$arID = array('');
		}
		return $arID;
	}

	/**
	 * Returns true if the user has set the flag "To all" in the list.
	 *
	 * @return bool
	 */
	public function IsGroupActionToAll()
	{
		return (isset($_REQUEST['action_target']) && $_REQUEST['action_target'] === 'selected');
	}

	/**
	 * @return void
	 */
	protected function PrepareAction()
	{
		if (!empty($_REQUEST['action_button']))
		{
			$_REQUEST['action'] = $_REQUEST['action_button'];
		}
	}

	/**
	 * @return string|null
	 */
	public function GetAction()
	{
		return (isset($_REQUEST['action']) ? $_REQUEST['action'] : null);
	}

	/**
	 * @return array|null
	 */
	protected function GetGroupIds()
	{
		$result = null;
		if (isset($_REQUEST['ID']))
		{
			$result = (!is_array($_REQUEST['ID']) ? array($_REQUEST['ID']) : $_REQUEST['ID']);
		}
		return $result;
	}

	public function ActionRedirect($url)
	{
		if ($this->isPublicMode)
		{
			$selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");
			if (strpos($url, $selfFolderUrl) === false)
			{
				$url = $selfFolderUrl.$url;
			}
		}

		if(strpos($url, "lang=")===false)
		{
			if(strpos($url, "?")===false)
				$url .= '?';
			else
				$url .= '&';
			$url .= 'lang='.LANGUAGE_ID;
		}
		return "BX.adminPanel.Redirect([], '".CUtil::AddSlashes($url)."', event);";
	}

	public function ActionAjaxReload($url)
	{
		if(strpos($url, "lang=")===false)
		{
			if(strpos($url, "?")===false)
				$url .= '?';
			else
				$url .= '&';
			$url .= 'lang='.LANGUAGE_ID;
		}
		return $this->table_id.".GetAdminList('".CUtil::AddSlashes($url)."');";
	}

	public function ActionPost($url = false, $action_name = false, $action_value = 'Y')
	{
		$res = '';
		if($url)
		{
			if(strpos($url, "lang=")===false)
			{
				if(strpos($url, "?")===false)
					$url .= '?';
				else
					$url .= '&';
				$url .= 'lang='.LANGUAGE_ID;
			}

			if(strpos($url, "mode=")===false)
				$url .= '&mode=frame';

			$res = 'BX(\'form_'.$this->table_id.'\').action=\''.CUtil::AddSlashes($url).'\';';
		}

		if ($action_name)
			return $res.'; BX.submit(document.forms.form_'.$this->table_id.', \''.CUtil::JSEscape($action_name).'\', \''.CUtil::JSEscape($action_value).'\');';
		else
			return $res.'; BX.submit(document.forms.form_'.$this->table_id.');';
	}

	public function ActionDoGroup($id, $action_id, $add_params='')
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;
		return $this->table_id.".GetAdminList('".CUtil::AddSlashes($APPLICATION->GetCurPage())."?ID=".CUtil::AddSlashes($id)."&action_button=".CUtil::AddSlashes($action_id)."&lang=".LANGUAGE_ID."&".bitrix_sessid_get().($add_params<>""?"&".CUtil::AddSlashes($add_params):"")."');";
	}

	public function InitFilter($arFilterFields)
	{
		//Filter by link from favorites. Extract fields.
		if(isset($_REQUEST['adm_filter_applied']) && intval($_REQUEST['adm_filter_applied']) > 0)
		{
			$dbRes = \CAdminFilter::GetList(array(), array('ID' => intval($_REQUEST['adm_filter_applied'])));

			if($row = $dbRes->Fetch())
			{
				$fields = unserialize($row['FIELDS']);

				if(is_array($fields) && !empty($fields))
				{
					foreach($fields as $field => $params)
					{
						if(isset($params['value']))
						{
							if(!isset($params['hidden']) || $params['hidden'] != 'true')
							{
								$GLOBALS[$field] = $params['value'];

								if($GLOBALS['set_filter'] != 'Y')
									$GLOBALS['set_filter'] = 'Y';
							}
						}
					}
				}
			}
		}

		$sTableID = $this->table_id;
		global $del_filter, $set_filter, $save_filter;
		if($del_filter <> "")
			DelFilterEx($arFilterFields, $sTableID);
		elseif($set_filter <> "")
		{
			CAdminFilter::UnEscape($arFilterFields);
			InitFilterEx($arFilterFields, $sTableID, "set");
		}
		elseif($save_filter <> "")
		{
			CAdminFilter::UnEscape($arFilterFields);
		}
		else
			InitFilterEx($arFilterFields, $sTableID, "get");

		foreach ($arFilterFields as $f)
		{
			$fperiod = $f."_FILTER_PERIOD";
			$fdirection = $f."_FILTER_DIRECTION";
			$fbdays = $f."_DAYS_TO_BACK";

			global $$f, $$fperiod, $$fdirection, $$fbdays;
			if (isset($$f))
				$this->filter[$f] = $$f;
			if (isset($$fperiod))
				$this->filter[$fperiod] = $$fperiod;
			if (isset($$fdirection))
				$this->filter[$fdirection] = $$fdirection;
			if (isset($$fbdays))
				$this->filter[$fbdays] = $$fbdays;
		}

		return $this->filter;
	}

	public function IsDefaultFilter()
	{
		global $set_default;
		$sTableID = $this->table_id;
		return $set_default=="Y" && (!isset($_SESSION["SESS_ADMIN"][$sTableID]) || empty($_SESSION["SESS_ADMIN"][$sTableID]));
	}

	public function &AddRow($id = false, $arRes = Array(), $link = false, $title = false)
	{
		$row = new CAdminListRow($this->aHeaders, $this->table_id);
		$row->id = $id;
		$row->arRes = $arRes;
		$row->link = $link;
		$row->title = $title;
		$row->pList = &$this;

		if($id)
		{
			if($this->bEditMode && in_array($id, $this->arEditedRows))
				$row->bEditMode = true;
			elseif(!empty($this->arUpdateErrorIDs) && in_array($id, $this->arUpdateErrorIDs))
				$row->bEditMode = true;
		}

		$this->aRows[] = &$row;
		return $row;
	}

	public function AddFooter($aFooter)
	{
		$this->aFooter = $aFooter;
	}

	public function NavText($sNavText)
	{
		$this->sNavText = $sNavText;
	}

	/**
	 * @param \Bitrix\Main\UI\PageNavigation $nav
	 * @param string $title
	 * @param bool $showAllways
	 * @param bool $post
	 */
	public function setNavigation(\Bitrix\Main\UI\PageNavigation $nav, $title, $showAllways = true, $post = false)
	{
		global $APPLICATION;

		ob_start();

		$APPLICATION->IncludeComponent(
			"bitrix:main.pagenavigation",
			"admin",
			array(
				"NAV_OBJECT" => $nav,
				"TITLE" => $title,
				"PAGE_WINDOW" => 10,
				"SHOW_ALWAYS" => $showAllways,
				"POST" => $post,
				"TABLE_ID" => $this->table_id,
			),
			false,
			array(
				"HIDE_ICONS" => "Y",
			)
		);

		$this->NavText(ob_get_clean());
	}

	public function Display()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		foreach(GetModuleEvents("main", "OnAdminListDisplay", true) as $arEvent)
			ExecuteModuleEventEx($arEvent, array(&$this));

		$errmsg = '';
		foreach ($this->arFilterErrors as $err)
			$errmsg .= ($errmsg<>''? '<br>': '').$err;
		foreach ($this->arUpdateErrors as $err)
			$errmsg .= ($errmsg<>''? '<br>': '').$err[0];
		foreach ($this->arGroupErrors as $err)
			$errmsg .= ($errmsg<>''? '<br>': '').$err[0];
		if($errmsg<>'')
			CAdminMessage::ShowMessage(array("MESSAGE"=>GetMessage("admin_lib_error"), "DETAILS"=>$errmsg, "TYPE"=>"ERROR"));

		$successMessage = '';
		for ($i = 0, $cnt = count($this->arActionSuccess); $i < $cnt; $i++)
			$successMessage .= ($successMessage != '' ? '<br>' : '').$this->arActionSuccess[$i];
		if ($successMessage != '')
			CAdminMessage::ShowMessage(array("MESSAGE" => GetMessage("admin_lib_success"), "DETAILS" => $successMessage, "TYPE" => "OK"));

		echo $this->sPrologContent;

		if($this->sContent===false)
		{
?>
<div class="adm-list-table-wrap<?=$this->context ? '' : ' adm-list-table-without-header'?><?=count($this->arActions)<=0 && !$this->bCanBeEdited ? ' adm-list-table-without-footer' : ''?>">
<?
		}

		if($this->context)
			$this->context->Show();

		if(
			(isset($_REQUEST['ajax_debugx']) && $_REQUEST['ajax_debugx']=='Y')
			|| (isset($_SESSION['AJAX_DEBUGX']) && $_SESSION['AJAX_DEBUGX'])
		)
			echo '<form method="POST" '.($this->bMultipart?' enctype="multipart/form-data" ':'').' onsubmit="CheckWin();ShowWaitWindow();" target="frame_debug" id="form_'.$this->table_id.'" name="form_'.$this->table_id.'" action="'.htmlspecialcharsbx($APPLICATION->GetCurPageParam("mode=frame", array("mode"))).'">';
		else
			echo '<form method="POST" '.($this->bMultipart?' enctype="multipart/form-data" ':'').' onsubmit="return BX.ajax.submitComponentForm(this, \''.$this->table_id.'_result_div\', true);" id="form_'.$this->table_id.'" name="form_'.$this->table_id.'" action="'.htmlspecialcharsbx($APPLICATION->GetCurPageParam("mode=frame", array("mode", "action", "action_button"))).'">';

		if($this->bEditMode && !$this->bCanBeEdited)
			$this->bEditMode = false;

		if($this->sContent!==false)
		{
			echo $this->sContent;
			echo '</form>';
			return;
		}

		$bShowSelectAll = (count($this->arActions)>0 || $this->bCanBeEdited);
		$this->bShowActions = false;
		foreach($this->aRows as $row)
		{
			if(!empty($row->aActions))
			{
				$this->bShowActions = true;
				break;
			}
		}

		//!!! insert filter's hiddens
		echo bitrix_sessid_post();
		//echo $this->sNavText;

		$colSpan = 0;
?>
<table class="adm-list-table" id="<?=$this->table_id;?>">
	<thead>
		<tr class="adm-list-table-header">
<?
		if($bShowSelectAll):
?>
			<td class="adm-list-table-cell adm-list-table-checkbox" onclick="this.firstChild.firstChild.click(); return BX.PreventDefault(event);"><div class="adm-list-table-cell-inner"><input class="adm-checkbox adm-designed-checkbox" type="checkbox" id="<?=$this->table_id?>_check_all" onclick="<?=$this->table_id?>.SelectAllRows(this); return BX.eventCancelBubble(event);" title="<?=GetMessage("admin_lib_list_check_all")?>" /><label for="<?=$this->table_id?>_check_all" class="adm-designed-checkbox-label"></label></div></td>
<?
			$colSpan++;
		endif;

		if($this->bShowActions):
?>
			<td class="adm-list-table-cell adm-list-table-popup-block" title="<?=GetMessage("admin_lib_list_act")?>"><div class="adm-list-table-cell-inner"></div></td>
<?
			$colSpan++;
		endif;

		foreach($this->aVisibleHeaders as $header):
			$bSort = $this->sort && !empty($header["sort"]);

			if ($bSort)
				$attrs = $this->sort->Show($header["content"], $header["sort"], $header["title"], "adm-list-table-cell");
			else
				$attrs = 'class="adm-list-table-cell"';

?>
			<td <?=$attrs?>>
				<div class="adm-list-table-cell-inner"><?=$header["content"]?></div>
			</td>
<?
			$colSpan++;
		endforeach;
?>
		</tr>
	</thead>
	<tbody>
<?
		if(!empty($this->aRows)):
			foreach($this->aRows as $row)
			{
				$row->Display();
			}
		elseif(!empty($this->aHeaders)):
?>
		<tr><td colspan="<?=$colSpan?>" class="adm-list-table-cell adm-list-table-empty"><?=GetMessage("admin_lib_no_data")?></td></tr>
<?
		endif;
?>
	</tbody>
</table>
<?
		$this->ShowActionTable();

// close form and div.adm-list-table-wrap

		echo $this->sEpilogContent;
		echo '
	</form>
</div>
';
		echo $this->sNavText;
	}

	public function DisplayExcel()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;
		echo '
		<html>
		<head>
		<title>'.$APPLICATION->GetTitle().'</title>
		<meta http-equiv="Content-Type" content="text/html; charset='.LANG_CHARSET.'">
		<style>
			td {mso-number-format:\@;}
			.number0 {mso-number-format:0;}
			.number2 {mso-number-format:Fixed;}
		</style>
		</head>
		<body>';

		echo "<table border=\"1\">";
		echo "<tr>";

		foreach($this->aVisibleHeaders as $header)
		{
			echo '<td>';
			echo $header["content"];
			echo '</td>';
		}
		echo "</tr>";


		foreach($this->aRows as $row)
		{
			echo "<tr>";
			foreach($this->aVisibleHeaders as $id=>$header_props)
			{
				$field = $row->aFields[$id];
				if(!is_array($row->arRes[$id]))
					$val = trim($row->arRes[$id]);
				else
					$val = $row->arRes[$id];

				switch($field["view"]["type"])
				{
					case "checkbox":
						if($val=='Y')
							$val = htmlspecialcharsex(GetMessage("admin_lib_list_yes"));
						else
							$val = htmlspecialcharsex(GetMessage("admin_lib_list_no"));
						break;
					case "select":
						if($field["edit"]["values"][$val])
							$val = htmlspecialcharsex($field["edit"]["values"][$val]);
						break;
					case "file":
						$arFile = CFile::GetFileArray($val);
						if(is_array($arFile))
							$val = htmlspecialcharsex(CHTTP::URN2URI($arFile["SRC"]));
						else
							$val = "";
						break;
					case "html":
						$val = trim(strip_tags($field["view"]['value'], "<br>"));
						break;
					default:
						$val = htmlspecialcharsex($val);
						break;
				}

				echo '<td';
				if ($header_props['align'])
					echo ' align="'.$header_props['align'].'"';
				if ($header_props['valign'])
					echo ' valign="'.$header_props['valign'].'"';
				if ($header_props['align'] === "right" && preg_match("/^([1-9][0-9]*|[1-9][0-9]*[.,][0-9]+)\$/", $val))
					echo ' class="number0"';
				echo '>';
				echo ($val<>""? $val: '&nbsp;');
				echo '</td>';
			}
			echo "</tr>";
		}

		echo "</table>";
		echo '</body></html>';
	}

	public function AddGroupActionTable($arActions, $arParams=array())
	{
		//array("action"=>"text", ...)
		//OR array(array("action" => "custom JS", "value" => "action", "type" => "button", "title" => "", "name" => ""), ...)
		$this->arActions = $arActions;
		//array("disable_action_target"=>true, "select_onchange"=>"custom JS")
		$this->arActionsParams = $arParams;
	}

	public function ShowActionTable()
	{
		if (empty($this->arActions) && !$this->bCanBeEdited)
			return;
?>
<div class="adm-list-table-footer" id="<?=$this->table_id?>_footer<?=$this->bEditMode || !empty($this->arUpdateErrorIDs) ? '_edit' : ''?>">
	<input type="hidden" name="action_button" id="<?=$this->table_id; ?>_action_button" value="" />
<?
		if($this->bEditMode || !empty($this->arUpdateErrorIDs)):
?>
		<input type="hidden" name="save" id="<?=$this->table_id?>_hidden_save" value="Y">
		<input type="submit" class="adm-btn-save" name="save" value="<?=GetMessage("admin_lib_list_edit_save")?>" title="<?=GetMessage("admin_lib_list_edit_save_title")?>" />
		<input type="button" onclick="BX('<?=$this->table_id?>_hidden_save').name='cancel'; <?=htmlspecialcharsbx($this->ActionPost(false, 'action_button', ''))?> " name="cancel" value="<?=GetMessage("admin_lib_list_edit_cancel")?>" title="<?=GetMessage("admin_lib_list_edit_cancel_title")?>" />

<?
		else: //($this->bEditMode || count($this->arUpdateErrorIDs)>0)
			if($this->arActionsParams["disable_action_target"] <> true):
?>
	<span class="adm-selectall-wrap"><input type="checkbox" class="adm-checkbox adm-designed-checkbox" name="action_target" value="selected" id="action_target" onclick="if(this.checked && !confirm('<?=CUtil::JSEscape(GetMessage("admin_lib_list_edit_for_all_warn"))?>')) {this.checked=false;} <?=$this->table_id?>.EnableActions();" title="<?=GetMessage("admin_lib_list_edit_for_all")?>" /><label for="action_target" class="adm-checkbox adm-designed-checkbox-label"></label><label title="<?=GetMessage("admin_lib_list_edit_for_all")?>" for="action_target" class="adm-checkbox-label"><?=GetMessage("admin_lib_list_for_all");?></label></span>
<?
			endif;

			$this->bCanBeDeleted = array_key_exists("delete", $this->arActions);

			if ($this->bCanBeEdited || $this->bCanBeDeleted)
			{
				echo '
	<span class="adm-table-item-edit-wrap'.(!$this->bCanBeEdited || !$this->bCanBeDeleted ? ' adm-table-item-edit-single' : '').'">
';
				if($this->bCanBeEdited)
				{
					echo '<a href="javascript:void(0)" class="adm-table-btn-edit adm-edit-disable" hidefocus="true" onclick="this.blur();if('.$this->table_id.'.IsActionEnabled(\'edit\')){document.forms[\'form_'.$this->table_id.'\'].elements[\'action_button\'].value=\'edit\'; '.
						htmlspecialcharsbx($this->ActionPost(false, 'action_button', 'edit')).'}" title="'.GetMessage("admin_lib_list_edit").'" id="action_edit_button"></a>';
				}
				if($this->bCanBeDeleted)
				{
					echo '<a href="javascript:void(0);" class="adm-table-btn-delete adm-edit-disable" hidefocus="true" onclick="this.blur();if('.$this->table_id.'.IsActionEnabled() && confirm((document.getElementById(\'action_target\') && document.getElementById(\'action_target\').checked? \''.GetMessage("admin_lib_list_del").'\':\''.GetMessage("admin_lib_list_del_sel").'\'))) {document.forms[\'form_'.$this->table_id.'\'].elements[\'action_button\'].value=\'delete\'; '.
						htmlspecialcharsbx($this->ActionPost(false, 'action_button', 'delete')).'}" title="'.GetMessage("admin_lib_list_del_title").'" class="context-button icon action-delete-button-dis" id="action_delete_button"></a>';
				}
				echo '
	</span>
';
			}

			$onchange = '';
			if (isset($this->arActionsParams["select_onchange"]))
			{
				if (is_array($this->arActionsParams["select_onchange"]))
				{
					$onchange = implode(' ', $this->arActionsParams["select_onchange"]);
				}
				elseif (is_string($this->arActionsParams["select_onchange"]))
				{
					$onchange = $this->arActionsParams["select_onchange"];
				}
			}

			$list = '';
			$html = '';
			$buttons = '';
			$actionList = array_filter($this->arActions);
			if (isset($actionList['delete']))
			{
				unset($actionList['delete']);
			}

			$allowedTypes = [
				'button' => true,
				'html' => true
			];

			foreach($actionList as $k=>$v)
			{
				if(is_array($v))
				{
					if (isset($v['type']) && isset($allowedTypes[$v['type']]))
					{
						switch ($v["type"])
						{
							case 'button':
								$buttons .= '<input type="button" name="" value="'.htmlspecialcharsbx($v['name']).'" onclick="'.(!empty($v["action"])? htmlspecialcharsbx($v['action']) : 'document.forms[\'form_'.$this->table_id.'\'].elements[\'action_button\'].value=\''.htmlspecialcharsbx($v["value"]).'\'; '.htmlspecialcharsbx($this->ActionPost()).'').'" title="'.htmlspecialcharsbx($v["title"]).'" />';
								break;
							case 'html':
								$html .= '<span class="adm-list-footer-ext">'.$v["value"].'</span>';
								break;
						}
					}
					else
					{
						$list .= '<option value="'.htmlspecialcharsbx($v['value']).'"'.($v['action']?' custom_action="'.htmlspecialcharsbx($v['action']).'"':'').'>'.htmlspecialcharsex($v['name']).'</option>';
					}
				}
				else
				{
					$list .= '<option value="'.htmlspecialcharsbx($k).'">'.htmlspecialcharsex($v).'</option>';
				}
			}
			unset($actionList, $k, $v);
			unset($allowedTypes);

			if ($buttons != '')
				echo '<span class="adm-list-footer-ext">'.$buttons.'</span>';

			if ($list != ''):
?>
	<span class="adm-select-wrap">
		<select name="action" id="<?=$this->table_id.'_action'; ?>" class="adm-select"<?=($onchange != '' ? ' onchange="'.htmlspecialcharsbx($onchange).'"':'')?>>
			<option value=""><?=GetMessage("admin_lib_list_actions")?></option>
<?=$list?>
		</select>
	</span>
<?
				if ($html != '')
					echo $html;
?>
	<input type="submit" name="apply" value="<?=GetMessage("admin_lib_list_apply")?>" onclick="if(this.form.action[this.form.action.selectedIndex].getAttribute('custom_action')){eval(this.form.action[this.form.action.selectedIndex].getAttribute('custom_action'));return false;}" disabled="disabled" class="adm-table-action-button" />
<?
			endif; //(strlen($list) > 0)
?>
	<span class="adm-table-counter" id="<?=$this->table_id?>_selected_count"><?=GetMessage('admin_lib_checked')?>: <span>0</span></span>
<?
		endif; // ($this->bEditMode || count($this->arUpdateErrorIDs)>0):
?>
</div>
<?
	}

	public function DisplayList($arParams = array())
	{
		$menu = new CAdminPopup($this->table_id."_menu", $this->table_id."_menu");
		$menu->Show();

		if(
			(isset($_REQUEST['ajax_debugx']) && $_REQUEST['ajax_debugx']=='Y')
			|| (isset($_SESSION['AJAX_DEBUGX']) && $_SESSION['AJAX_DEBUGX'])
		)
		{
			echo '<script>
				function CheckWin()
				{
					window.open("about:blank", "frame_debug");
				}
				</script>';
		}
		else
		{
			echo '<iframe src="javascript:\'\'" id="frame_'.$this->table_id.'" name="frame_'.$this->table_id.'" style="width:1px; height:1px; border:0px; position:absolute; left:-10px; top:-10px; z-index:0;"></iframe>';
		}

		$aUserOpt = CUserOptions::GetOption("global", "settings");

		if (!is_array($arParams))
			$arParams = array();

		if (!isset($arParams['FIX_HEADER']))
			$arParams['FIX_HEADER'] = true;
		if (!isset($arParams['FIX_FOOTER']))
			$arParams['FIX_FOOTER'] = true;
		if (!isset($arParams['context_ctrl']))
			$arParams['context_ctrl'] = ($aUserOpt["context_ctrl"] == "Y");
		if (!isset($arParams['context_menu']))
			$arParams['context_menu'] = ($aUserOpt["context_menu"] <> "N");

		$tbl = CUtil::JSEscape($this->table_id);
?>
<script type="text/javascript">
window['<?=$tbl?>'] = new BX.adminList('<?=$tbl?>', <?=CUtil::PhpToJsObject($arParams)?>);
BX.adminChain.addItems("<?=$tbl?>_navchain_div");
</script>
<?

		echo '<div id="'.$this->table_id.'_result_div" class="adm-list-table-layout">';
		$this->Display();
		echo '</div>';
	}

	public function AddUpdateError($strError, $id = false)
	{
		$this->arUpdateErrors[] = Array($strError, $id);
		$this->arUpdateErrorIDs[] = $id;
	}

	public function AddGroupError($strError, $id = false)
	{
		$this->arGroupErrors[] = Array($strError, $id);
		$this->arGroupErrorIDs[] = $id;
	}

	public function AddActionSuccessMessage($strMessage)
	{
		$this->arActionSuccess[] = $strMessage;
	}

	public function AddFilterError($strError)
	{
		$this->arFilterErrors[] = $strError;
	}

	public function BeginPrologContent()
	{
		ob_start();
	}

	public function EndPrologContent()
	{
		$this->sPrologContent .= ob_get_contents();
		ob_end_clean();
	}

	public function BeginEpilogContent()
	{
		ob_start();
	}

	public function EndEpilogContent()
	{
		$this->sEpilogContent .= ob_get_contents();
		ob_end_clean();
	}

	public function BeginCustomContent()
	{
		ob_start();
	}

	public function EndCustomContent()
	{
		$this->sContent = ob_get_contents();
		ob_end_clean();
	}

	public function CreateChain()
	{
		return new CAdminChain($this->table_id."_navchain_div", false);
	}

	/**
	 * @param CAdminChain $chain
	 */
	public function ShowChain($chain)
	{
		$this->BeginPrologContent();
		$chain->Show();
		$this->EndPrologContent();
	}

	public function CheckListMode()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		if (!isset($_REQUEST["mode"]))
			return;

		if($_REQUEST["mode"]=='list' || $_REQUEST["mode"]=='frame')
		{
			ob_start();
			$this->Display();
			$string = ob_get_contents();
			ob_end_clean();

			if($_REQUEST["mode"]=='frame')
			{
?>
<html><head></head><body><?=$string?><script type="text/javascript">
	var topWindow = (window.BX||window.parent.BX).PageObject.getRootWindow();
	topWindow.bxcompajaxframeonload = function() {
	topWindow.BX.adminPanel.closeWait();
	topWindow.<?=$this->table_id?>.Destroy(false);
	topWindow.<?=$this->table_id?>.Init();
<?
				if(isset($this->onLoadScript)):
?>
	topWindow.BX.evalGlobal('<?=CUtil::JSEscape($this->onLoadScript)?>');
<?
				endif;
?>
};
topWindow.BX.ajax.UpdatePageData({});
</script></body></html>
<?
			}
			else
			{
				if(isset($this->onLoadScript)):
?>
<script type="text/javascript"><?=$this->onLoadScript?></script>
<?
				endif;

				echo $string;
			}
			define("ADMIN_AJAX_MODE", true);
			require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
			die();
		}
		elseif($_REQUEST["mode"]=='excel')
		{
			$fname = basename($APPLICATION->GetCurPage(), ".php");
			// http response splitting defence
			$fname = str_replace(array("\r", "\n"), "", $fname);

			header("Content-Type: application/vnd.ms-excel");
			header("Content-Disposition: filename=".$fname.".xls");
			$this->DisplayExcel();
			require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
			die();
		}
	}
}

class CAdminListRow
{
	var $aHeaders = array();
	var $aHeadersID = array();
	var $aFields = array();
	var $aActions = array();
	var $table_id;
	var $indexFields = 0;
	var $edit = false;
	var $id;
	var $bReadOnly = false;
	var $aFeatures = array();
	var $bEditMode = false;
	var $arRes;
	var $link;
	var $title;
	var $pList;
	var $isPublicMode = false;

	/**
	* CAdminListRow constructor.
	* @param array &$aHeaders
	* @param string $table_id
	*/
	public function __construct(&$aHeaders, $table_id)
	{
		$this->aHeaders = $aHeaders;
		$this->aHeadersID = array_keys($aHeaders);
		$this->table_id = $table_id;

		$this->isPublicMode = (defined("PUBLIC_MODE") && PUBLIC_MODE == 1);
	}

	/** @deprecated
	* @param array &$aHeaders
	* @param string $table_id
	*/
	public function CAdminListRow(&$aHeaders, $table_id)
	{
		self::__construct($aHeaders, $table_id);
	}

	function SetFeatures($aFeatures)
	{
		//array("footer"=>true)
		$this->aFeatures = $aFeatures;
	}

	function AddField($id, $text, $edit=false, $isHtml = true)
	{
		$this->aFields[$id] = array();
		if ($edit !== false)
		{
			$this->aFields[$id]["edit"] = array("type" => "input", "value" => $edit);
			$this->pList->bCanBeEdited = true;
		}
		$type = $isHtml ? "html" : "text";
		$this->aFields[$id]["view"] = array("type" => $type, "value" => $text);
	}

	/**
	 * @param string $id
	 * @param array|boolean $arAttributes
	 * @return void
	 */
	function AddCheckField($id, $arAttributes = Array())
	{
		if($arAttributes!==false)
		{
			$this->aFields[$id]["edit"] = Array("type"=>"checkbox", "attributes"=>$arAttributes);
			$this->pList->bCanBeEdited = true;
		}
		$this->aFields[$id]["view"] = Array("type"=>"checkbox");
	}

	/**
	 * @param string $id
	 * @param array $arValues
	 * @param array|boolean $arAttributes
	 * @return void
	 */
	function AddSelectField($id, $arValues = Array(), $arAttributes = Array())
	{
		if($arAttributes!==false)
		{
			$this->aFields[$id]["edit"] = Array("type"=>"select", "values"=>$arValues, "attributes"=>$arAttributes);
			$this->pList->bCanBeEdited = true;
		}
		$this->aFields[$id]["view"] = Array("type"=>"select", "values"=>$arValues);
	}

	/**
	 * @param string $id
	 * @param array|boolean $arAttributes
	 * @return void
	 */
	function AddInputField($id, $arAttributes = Array())
	{
		if($arAttributes!==false)
		{
			$this->aFields[$id]["edit"] = Array("type"=>"input", "attributes"=>$arAttributes);
			$this->pList->bCanBeEdited = true;
		}
	}

	/**
	 * @param string $id
	 * @param array|boolean $arAttributes
	 * @param bool $useTime
	 * @return void
	 */
	function AddCalendarField($id, $arAttributes = Array(), $useTime = false)
	{
		if($arAttributes!==false)
		{
			$this->aFields[$id]["edit"] = array("type"=>"calendar", "attributes"=>$arAttributes, "useTime" => $useTime);
			$this->pList->bCanBeEdited = true;
		}
	}

	function AddViewField($id, $sHTML)
	{
		$this->aFields[$id]["view"] = Array("type"=>"html", "value"=>$sHTML);
	}

	function AddEditField($id, $sHTML)
	{
		$this->aFields[$id]["edit"] = Array("type"=>"html", "value"=>$sHTML);
		$this->pList->bCanBeEdited = true;
	}

	/**
	 * @param string $id
	 * @param bool|array $showInfo
	 * @return void
	 */
	function AddViewFileField($id, $showInfo = false)
	{
		static $fileman = 0;
		if (!($fileman++))
			CModule::IncludeModule('fileman');

		$this->aFields[$id]["view"] = array(
			"type" => "file",
			"showInfo" => $showInfo,
			"inputs" => array(
				'upload' => false,
				'medialib' => false,
				'file_dialog' => false,
				'cloud' => false,
				'del' => false,
				'description' => false,
			),
		);
	}

	/**
	 * @param string $id
	 * @param bool|array $showInfo
	 * @param array $inputs
	 * @return void
	 */
	function AddFileField($id, $showInfo = false, $inputs = array())
	{
		$this->aFields[$id]["edit"] = array(
			"type" => "file",
			"showInfo" => $showInfo,
			"inputs" => $inputs,
		);
		$this->pList->bCanBeEdited = true;
		$this->AddViewFileField($id, $showInfo);
	}

	function AddActions($aActions)
	{
		if (is_array($aActions))
			$this->aActions = $aActions;
	}

	function __AttrGen($attr)
	{
		$res = '';
		foreach($attr as $name=>$val)
			$res .= ' '.htmlspecialcharsbx($name).'="'.htmlspecialcharsbx($val).'"';

		return $res;
	}

	function VarsFromForm()
	{
		return ($this->bEditMode && is_array($this->pList->arUpdateErrorIDs) && in_array($this->id, $this->pList->arUpdateErrorIDs));
	}

	function Display()
	{
		$sDefAction = $sDefTitle = "";

		if(!$this->bEditMode)
		{
			if(!empty($this->link))
			{
				$sDefAction = $this->getActionLink($this->link);
				$sDefTitle = $this->title;
			}
			else
			{
				foreach($this->aActions as $action)
				{
					if($action["DEFAULT"] == true)
					{
						$sDefAction = $this->getActionsItemLink($action);
						$sDefTitle = (!empty($action["TITLE"])? $action["TITLE"] : $action["TEXT"]);
						break;
					}
				}
			}

			$sDefAction = htmlspecialcharsbx($sDefAction);
			$sDefTitle = htmlspecialcharsbx($sDefTitle);
		}

		$sMenuItems = "";
		if(!empty($this->aActions))
			$sMenuItems = htmlspecialcharsbx(CAdminPopup::PhpToJavaScript($this->aActions));
?>
<tr class="adm-list-table-row<?=(isset($this->aFeatures["footer"]) && $this->aFeatures["footer"] == true? ' footer':'')?><?=$this->bEditMode?' adm-table-row-active' : ''?>"<?=($sMenuItems <> ""? ' oncontextmenu="return '.$sMenuItems.';"':'');?><?=($sDefAction <> ""? ' ondblclick="'.$sDefAction.'"'.(!empty($sDefTitle)? ' title="'.GetMessage("admin_lib_list_double_click").' '.$sDefTitle.'"':''):'')?>>
<?

		if(count($this->pList->arActions)>0 || $this->pList->bCanBeEdited):
			$check_id = RandString(5);
?>
	<td class="adm-list-table-cell adm-list-table-checkbox adm-list-table-checkbox-hover<?=$this->bReadOnly? ' adm-list-table-checkbox-disabled':''?>"><input type="checkbox" class="adm-checkbox adm-designed-checkbox" name="ID[]" id="<?=$this->table_id."_".$this->id."_".$check_id;?>" value="<?=$this->id?>" autocomplete="off" title="<?=GetMessage("admin_lib_list_check")?>"<?=$this->bReadOnly? ' disabled="disabled"':''?><?=$this->bEditMode ? ' checked="checked" disabled="disabled"' : ''?> /><label class="adm-designed-checkbox-label adm-checkbox" for="<?=$this->table_id."_".$this->id."_".$check_id;?>"></label></td>
<?
		endif;

		if($this->pList->bShowActions):
			if(!empty($this->aActions)):
?>
	<td class="adm-list-table-cell adm-list-table-popup-block" onclick="BX.adminList.ShowMenu(this.firstChild, this.parentNode.oncontextmenu(), this.parentNode);"><div class="adm-list-table-popup" title="<?=GetMessage("admin_lib_list_actions_title")?>"></div></td>
<?
			else:
?>
	<td class="adm-list-table-cell"></td>
<?
			endif;
		endif;

		end($this->pList->aVisibleHeaders);
		$last_id = key($this->pList->aVisibleHeaders);
		reset($this->pList->aVisibleHeaders);

		$bVarsFromForm = ($this->bEditMode && is_array($this->pList->arUpdateErrorIDs) && in_array($this->id, $this->pList->arUpdateErrorIDs));
		foreach($this->pList->aVisibleHeaders as $id=>$header_props)
		{
			$field = $this->aFields[$id];
			if($this->bEditMode && isset($field["edit"]))
			{
				if($bVarsFromForm && $_REQUEST["FIELDS"])
					$val = $_REQUEST["FIELDS"][$this->id][$id];
				else
					$val = $this->arRes[$id];

				$val_old = $this->arRes[$id];

				echo '<td class="adm-list-table-cell',
					(isset($header_props['align']) && $header_props['align']? ' align-'.$header_props['align']: ''),
					(isset($header_props['valign']) && $header_props['valign']? ' valign-'.$header_props['valign']: ''),
					($id === $last_id? ' adm-list-table-cell-last': ''),
				'">';

				if(is_array($val_old))
				{
					foreach($val_old as $k=>$v)
						echo '<input type="hidden" name="FIELDS_OLD['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']['.htmlspecialcharsbx($k).']" value="'.htmlspecialcharsbx($v).'">';
				}
				else
				{
					echo '<input type="hidden" name="FIELDS_OLD['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']" value="'.htmlspecialcharsbx($val_old).'">';
				}
				switch($field["edit"]["type"])
				{
					case "checkbox":
						echo '<input type="hidden" name="FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']" value="N">';
						echo '<input type="checkbox" name="FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']" value="Y"'.($val=='Y' || $val === true?' checked':'').'>';
						break;
					case "select":
						echo '<select name="FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']"'.$this->__AttrGen($field["edit"]["attributes"]).'>';
						foreach($field["edit"]["values"] as $k=>$v)
							echo '<option value="'.htmlspecialcharsbx($k).'" '.($k==$val?' selected':'').'>'.htmlspecialcharsbx($v).'</option>';
						echo '</select>';
						break;
					case "input":
						if(!$field["edit"]["attributes"]["size"])
							$field["edit"]["attributes"]["size"] = "10";
						echo '<input type="text" '.$this->__AttrGen($field["edit"]["attributes"]).' name="FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']" value="'.htmlspecialcharsbx($val).'">';
						break;
					case "calendar":
						if(!$field["edit"]["attributes"]["size"])
							$field["edit"]["attributes"]["size"] = "10";
						echo '<span style="white-space:nowrap;"><input type="text" '.$this->__AttrGen($field["edit"]["attributes"]).' name="FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']" value="'.htmlspecialcharsbx($val).'">';
						echo CAdminCalendar::Calendar(
								'FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']',
								'',
								'',
								$field['edit']['useTime']
							).'</span>';
						break;
					case "file":
						echo CFileInput::Show(
							'FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']',
							$val,
							$field["edit"]["showInfo"],
							$field["edit"]["inputs"]
						);
						break;
					default:
						echo $field["edit"]['value'];
				}
				echo '</td>';
			}
			else
			{
				if(is_string($this->arRes[$id]))
					$val = trim($this->arRes[$id]);
				else
					$val = $this->arRes[$id];

				if(isset($field["view"]))
				{
					switch($field["view"]["type"])
					{
						case "checkbox":
							if($val == 'Y' || $val === true)
								$val = htmlspecialcharsex(GetMessage("admin_lib_list_yes"));
							else
								$val = htmlspecialcharsex(GetMessage("admin_lib_list_no"));
							break;
						case "select":
							if($field["edit"]["values"][$val])
								$val = htmlspecialcharsex($field["edit"]["values"][$val]);
							else
								$val = htmlspecialcharsex($val);
							break;
						case "file":
							if ($val > 0)
								$val = CFileInput::Show(
									'NO_FIELDS['.htmlspecialcharsbx($this->id).']['.htmlspecialcharsbx($id).']',
									$val,
									$field["view"]["showInfo"],
									$field["view"]["inputs"]
								);
							else
								$val = '';
							break;
						case "html":
							$val = $field["view"]['value'];
							break;
						default:
							$val = htmlspecialcharsex($val);
							break;
					}
				}
				else
				{
					$val = htmlspecialcharsex($val);
				}

				echo '<td class="adm-list-table-cell',
					(isset($header_props['align']) && $header_props['align']? ' align-'.$header_props['align']: ''),
					(isset($header_props['valign']) && $header_props['valign']? ' valign-'.$header_props['valign']: ''),
					($id === $last_id? ' adm-list-table-cell-last': ''),
				'">';
				echo ((string)$val <> ""? $val: '&nbsp;');
				if(isset($field["edit"]) && $field["edit"]["type"] == "calendar")
					CAdminCalendar::ShowScript();
				echo '</td>';
			}
		}
?>
</tr>
<?
	}

	/**
	 * @param string $url
	 * @return string
	 */
	protected function getActionLink($url)
	{
		global $adminSidePanelHelper;
		if (is_object($adminSidePanelHelper) && $adminSidePanelHelper->isPublicSidePanel())
			return "BX.adminSidePanel.onOpenPage('".CUtil::JSEscape($url)."');";
		return "BX.adminPanel.Redirect([], '".CUtil::JSEscape($url)."', event);";
	}

	/**
	* @param array $item
	* @return bool
	*/
	protected function getActionsItemLink(array $item)
	{
		return (!empty($item["ACTION"])
			? $item["ACTION"]
			: $this->getActionLink($item["LINK"])
		);
	}
}epilog_auth_admin.php000066400000003071147732346240010744 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

if (isset($_REQUEST['bxsender']))
	return;

include($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/interface/lang_files.php");
?>

	</div><?//login-main-wrapper?>

	<div style="display: none;" id="window_wrapper"></div>

<script type="text/javascript">
BX.ready(BX.defer(function(){
	BX.addClass(document.body, 'login-animate');
	BX.addClass(document.body, 'login-animate-popup');
<?
$arPreload = array(
	'CSS' => array('/bitrix/panel/main/admin.css', '/bitrix/panel/main/admin-public.css', '/bitrix/panel/main/adminstyles_fixed.css', '/bitrix/themes/.default/modules.css'),
	'JS' => array('/bitrix/js/main/utils.js', '/bitrix/js/main/admin_tools.js', '/bitrix/js/main/popup_menu.js', '/bitrix/js/main/admin_search.js', '/bitrix/js/main/dd.js','/bitrix/js/main/date/main.date.js','/bitrix/js/main/core/core_date.js', '/bitrix/js/main/core/core_admin_interface.js', '/bitrix/js/main/core/core_autosave.js', '/bitrix/js/main/core/core_fx.js'),
);
foreach ($arPreload['CSS'] as $key=>$file)
	$arPreload['CSS'][$key] = CUtil::GetAdditionalFileURL($file,true);
foreach ($arPreload['JS'] as $key=>$file)
	$arPreload['JS'][$key] = CUtil::GetAdditionalFileURL($file,true);
?>

	//preload admin scripts&styles
	setTimeout(function() {
		BX.load(['<?=implode("','",$arPreload['CSS'])?>']);
		BX.load(['<?=implode("','",$arPreload['JS'])?>']);
	}, 2000);
}));

new BX.COpener({DIV: 'login_lang_button', ACTIVE_CLASS: 'login-language-btn-active', MENU: <?=CUtil::PhpToJsObject($arLangButton['MENU'])?>});
</script>
</body>
</html>
get_menu.php000064400000001176147732346240007101 0ustar00<?
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_js.php");

$_REQUEST["admin_mnu_menu_id"] = urldecode($_REQUEST["admin_mnu_menu_id"]);
$adminMenu->AddOpenedSections($_REQUEST["admin_mnu_menu_id"]);
$adminMenu->Init(array($_REQUEST["admin_mnu_module_id"]));
$adminMenu->ShowSubmenu($_REQUEST["admin_mnu_menu_id"]);

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin_js.php");
?>
jspopup.php000064400000014532147732346240006776 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

class CJSPopup
{
	var $__form_name = 'bx_popup_form';
	var $post_args;
	var $title = '';
	var $bDescriptionStarted = false;
	var $bContentStarted = false;
	var $bButtonsStarted = false;
	var $suffix = '';
	var $jsPopup = 'BX.WindowManager.Get()';
	var $bContentBuffered;
	var $cont_id;

	var $bInited = false;

	/*
	$arConfig = array(
		'TITLE' => 'Popup window title',
		'ARGS' => 'param1=values1&param2=value2', // additional GET arguments for POST query
	)
	*/
	public function __construct($title = '', $arConfig = array())
	{
		if ($title != '') $this->SetTitle($title);
		if (is_set($arConfig, 'TITLE')) $this->SetTitle($arConfig['TITLE']);
		if (is_set($arConfig, 'ARGS')) $this->SetAdditionalArgs($arConfig['ARGS']);
		if (is_set($arConfig, 'SUFFIX') && strlen($arConfig['SUFFIX']) > 0) $this->SetSuffix($arConfig['SUFFIX']);
	}

	function InitSystem()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		if (!$this->bInited && $_REQUEST['bxsender'] != 'core_window_cauthdialog')
		{
			$this->InitScripts();

			$APPLICATION->AddBufferContent(array($this, "_InitSystem"));

			$APPLICATION->ShowHeadStrings();
			$APPLICATION->ShowHeadScripts();

			$this->bInited = true;
		}
	}

	function _InitSystem()
	{
		$adminPage = new CAdminPage();

		echo $adminPage->ShowPopupCSS();
		echo $adminPage->ShowScript();

	}

	function InitScripts()
	{
		CJSCore::Init(array('admin_interface'));
	}

	function SetAdditionalArgs($additional_args = '')
	{
		$this->post_args = $additional_args;
	}

	function SetTitle($title = '')
	{
		$this->title = trim($title);
	}

	function GetFormName()
	{
		return $this->__form_name;
	}

	function SetSuffix($suffix)
	{
		$this->suffix = '_'.trim($suffix);
		$this->__form_name .= $this->suffix;
	}

	function ShowTitlebar($title = '')
	{
		$this->InitSystem();

		if ($title == '')
			$title = $this->title;
		?>
		<script type="text/javascript">
			var currentWindow = top.window;
			if (top.BX.SidePanel.Instance && top.BX.SidePanel.Instance.getTopSlider())
			{
				currentWindow = top.BX.SidePanel.Instance.getTopSlider().getWindow();
			}
			currentWindow.<?=$this->jsPopup?>.SetTitle('<?echo CUtil::JSEscape($title)?>');
		</script>
		<?
	}

	function StartDescription($icon = false)
	{
		$this->InitSystem();

		$this->bDescriptionStarted = true;
?>
<script type="text/javascript"><?if ($icon):?>
	<?if (strpos($icon, '/') === false):?>

		<?=$this->jsPopup?>.SetIcon('<?echo CUtil::JSEscape($icon)?>');
	<?else:?>

		<?=$this->jsPopup?>.SetIconFile('<?echo CUtil::JSEscape($icon)?>');
	<?endif;?>
<?endif;?>
<?
			ob_start();
	}

	function EndDescription()
	{
		if ($this->bDescriptionStarted)
		{
			$descr = ob_get_contents();
			ob_end_clean();
?>

<?=$this->jsPopup?>.SetHead('<?echo CUtil::JSEscape($descr)?>');</script>
<?
			//echo '</div></div>';
			$this->bDescriptionStarted = false;
		}
	}

	function StartContent($arAdditional = array())
	{
		$this->InitSystem();

		$this->EndDescription();
		$this->bContentStarted = true;

		if ($arAdditional['buffer'])
		{
			$this->bContentBuffered = true;
			//ob_start();
			$this->cont_id = RandString(10);
			echo '<div id="'.$this->cont_id.'" style="display: none;">';
		}

		echo '<form name="'.$this->__form_name.'">'."\r\n";
		echo bitrix_sessid_post()."\r\n";

		if (is_set($_REQUEST, 'back_url'))
			echo '<input type="hidden" name="back_url" value="'.htmlspecialcharsbx($_REQUEST['back_url']).'" />'."\r\n";
	}

	function EndContent()
	{
		if ($this->bContentStarted)
		{
			echo '</form>'."\r\n";

			$hkInstance = CHotKeys::getInstance();
			$Execs = $hkInstance->GetCodeByClassName("CDialog");
			echo $hkInstance->PrintJSExecs($Execs, "", true, true);

			if ($this->bContentBuffered)
			{
?></div><script type="text/javascript">BX.ready(function() {<?=$this->jsPopup?>.SwapContent(BX('<?echo $this->cont_id?>'))});</script><?
			}

			if (!defined('BX_PUBLIC_MODE') || BX_PUBLIC_MODE == false)
			{
?><script type="text/javascript"><?echo "BX.adminFormTools.modifyFormElements(".$this->jsPopup.".DIV);"?></script><?
			}

			$this->bContentStarted = false;
		}
	}

	function StartButtons()
	{
		$this->InitSystem();

		$this->EndDescription();
		$this->EndContent();

		$this->bButtonsStarted = true;

		ob_start();
	}

	function EndButtons()
	{
		if ($this->bButtonsStarted)
		{
			$buttons = ob_get_contents();
			ob_end_clean();
?>
		<script type="text/javascript"><?=$this->jsPopup?>.SetButtons('<?echo CUtil::JSEscape($buttons)?>');</script>
<?
			$this->bButtonsStarted = false;
		}
	}

	function ShowStandardButtons($arButtons = array('save', 'cancel'))
	{
		$this->InitSystem();

		if (!is_array($arButtons)) return;

		if ($this->bButtonsStarted)
		{
			$this->EndButtons();
		}

		$arSB = array('save' => $this->jsPopup.'.btnSave', 'cancel' => $this->jsPopup.'.btnCancel', 'close' => $this->jsPopup.'.btnClose');

		foreach ($arButtons as $key => $value)
			if (!$arSB[$value]) unset($arButtons[$key]);
		$arButtons = array_values($arButtons);

?>
<script type="text/javascript"><?=$this->jsPopup?>.SetButtons([<?
	foreach ($arButtons as $key => $btn)
		echo ($key ? ',' : '').$arSB[$btn];
?>]);</script><?
	}

	function ShowValidationError($errortext)
	{
		$this->EndDescription();
		echo '<script>top.'.$this->jsPopup.'.ShowError(\''.CUtil::JSEscape(str_replace(array('<br>', '<br />', '<BR>', '<BR />'), "\r\n", $errortext)).'\')</script>';
	}

	function ShowError($errortext, $title = '')
	{
		$this->ShowTitlebar($title != "" ? $title : $this->title);

		if (!$this->bDescriptionStarted)
			$this->StartDescription();

		ShowError($errortext);

		$this->ShowStandardButtons(array("close"));
		echo '<script>'.$this->jsPopup.'.AdjustShadow();</script>';
		require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin_js.php");

		exit();
	}

	function Close($bReload = true, $back_url = false)
	{
		if (!$back_url && is_set($_REQUEST, 'back_url'))
			$back_url = $_REQUEST['back_url'];

		if(substr($back_url, 0, 1) != "/" || substr($back_url, 1, 1) == "/")
		{
			//only local /url is allowed
			$back_url = '';
		}

		echo '<script>';
		echo 'top.'.$this->jsPopup.'.Close(); ';

		if ($bReload)
		{
			echo 'top.BX.showWait(); ';
			echo "top.BX.reload('".CUtil::JSEscape($back_url)."', true);";
		}
		echo '</script>';
		die();
	}
}

class CJSPopupOnPage extends CJSPopup
{
	function InitSystem() {} // this SHOULD be empty!
}
prolog_auth_admin.php000064400000006337147732346240010775 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

if (isset($_REQUEST['bxsender']))
{
	if ($_REQUEST['bxsender'] == 'core_window_cauthdialog')
	{
		echo '<meta http-equiv="Content-Type" content="text/html; charset='.LANG_CHARSET.'" />'."\n";
		$APPLICATION->ShowCSS();
		$APPLICATION->ShowHeadStrings();
		$APPLICATION->ShowHeadScripts();
	}
	return;
}

IncludeModuleLangFile(__FILE__);
IncludeModuleLangFile(dirname(__FILE__)."/epilog_main_admin.php");
IncludeModuleLangFile(dirname(__FILE__)."/epilog_auth_admin.php");

if(strlen($APPLICATION->GetTitle())<=0)
	$APPLICATION->SetTitle(GetMessage("MAIN_PROLOG_ADMIN_AUTH_TITLE"));

$aUserOpt = CUserOptions::GetOption("admin_panel", "settings");

$direction = "";
$direct = CLanguage::GetByID(LANGUAGE_ID);
$arDirect = $direct->Fetch();
if($arDirect["DIRECTION"] == "N")
	$direction = ' dir="rtl"';

$arLangs = CLanguage::GetLangSwitcherArray();

$arLangButton = array();
$arLangMenu = array();

foreach($arLangs as $adminLang)
{
	if ($adminLang['SELECTED'])
	{
		$arLangButton = array(
			"TEXT"=>ToUpper($adminLang["LID"]),
			"TITLE"=>$adminLang["NAME"],
			"LINK"=>htmlspecialcharsback($adminLang["PATH"]),
			"SECTION" => 1,
			"ICON" => "adm-header-language",
		);
	}

	$arLangMenu[] = array(
		"TEXT" => '('.$adminLang["LID"].') '.$adminLang["NAME"],
		"LINK"=>htmlspecialcharsback($adminLang["PATH"]),
	);
}

if (count($arLangMenu) > 1)
{
	$arLangButton['MENU'] = $arLangMenu;
}


//Footer
$vendor = COption::GetOptionString("main", "vendor", "1c_bitrix");

$bxProductConfig = array();
if(file_exists($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/.config.php"))
	include($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/.config.php");

//wizard customization file
if(isset($bxProductConfig["admin"]["copyright"]))
	$sCopyright = $bxProductConfig["admin"]["copyright"];
else
	$sCopyright = GetMessage("EPILOG_ADMIN_POWER").' <a href="'.GetMessage("EPILOG_ADMIN_URL_PRODUCT_".$vendor).'">'.GetMessage("EPILOG_ADMIN_SM_".$vendor).'#VERSION#</a>. '.GetMessage("EPILOG_ADMIN_COPY_".$vendor);
$sVer = ($GLOBALS['USER']->CanDoOperation('view_other_settings')? " ".SM_VERSION : "");
$sCopyright = str_replace("#VERSION#", $sVer, $sCopyright);

if(isset($bxProductConfig["admin"]["links"]))
	$sLinks = $bxProductConfig["admin"]["links"];
else
	$sLinks = '<a href="'.GetMessage("EPILOG_ADMIN_URL_SUPPORT_".$vendor).'" class="login-footer-link">'.GetMessage("epilog_support_link").'</a>';

CJSCore::Init(array('admin_login'));
?>
<!DOCTYPE html>
<html<?=$direction?>>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, width=device-width">
<?
echo '<meta http-equiv="Content-Type" content="text/html; charset='.LANG_CHARSET.'" />'."\n";
$APPLICATION->ShowCSS();
$APPLICATION->ShowHeadStrings();
$APPLICATION->ShowHeadScripts();
?>
<title><?echo htmlspecialcharsex($APPLICATION->GetTitle(false, true))?> - <?echo COption::GetOptionString("main","site_name", $_SERVER["SERVER_NAME"])?></title>
</head>
<body id="bx-admin-prefix">
<!--[if lte IE 7]>
<style type="text/css">
#login_wrapper {display:none !important;}
</style>
<div id="bx-panel-error">
<?echo GetMessage("admin_panel_browser")?>
</div><![endif]-->
	<div id="login_wrapper" class="login-page login-page-bg login-main-wrapper">
epilog_popup_admin.php000064400000000020147732346240011133 0ustar00</body>
</html>init_admin.php000066400000001677147732346240007421 0ustar00<?php
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");
define("ADMIN_THEME_ID", CAdminTheme::GetCurrentTheme());

global $adminPage, $adminMenu, $adminChain, $adminAjaxHelper, $adminSidePanelHelper;
$adminPage = new CAdminPage();
if(class_exists('CAdminAjaxHelper'))
{
	//updater sequence
	$adminAjaxHelper = new CAdminAjaxHelper();
}
$adminSidePanelHelper = new CAdminSidePanelHelper();
$adminMenu = new CAdminMenu();
$adminChain = new CAdminMainChain("main_navchain");

// todo: a temporary solution for blocking access to admin pages bypassing the interface
if (defined("SELF_FOLDER_URL") && !$adminSidePanelHelper->isPublicSidePanel() && !defined("INTERNAL_ADMIN_PAGE") && !isset($_REQUEST["bxpublic"]) && !isset($_REQUEST["public"]))
{
	if (IsModuleInstalled("bitrix24"))
	{
		LocalRedirect("/");
	}
	else
	{
		$APPLICATION->AuthForm("");
	}
}
settings_admin_form.php000066400000023421147732346240011330 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

if (!isset($adminFormParams) || !is_array($adminFormParams))
{
	$adminFormParams = array(
		'tabPrefix' => 'cedit'
	);
}
$jsAdminFormParams = CUtil::PhpToJSObject($adminFormParams);

$arSystemTabsFields = array();

foreach($this->arSystemTabs as $arTab)
{
	if(!array_key_exists("CUSTOM", $arTab) || $arTab["CUSTOM"] !== "Y")
	{
		$arSystemTabsFields[$arTab["DIV"]] = array();
		if(is_array($arTab["FIELDS"]))
		{
			foreach($arTab["FIELDS"] as $i => $arField)
			{
				$arSystemTabsFields[$arTab["DIV"]][$arField["id"]] = $arField["id"];
			}
		}
	}
}

$arSystemTabs = array();
foreach($this->arSystemTabs as $arTab)
{
	if(!array_key_exists("CUSTOM", $arTab) || $arTab["CUSTOM"] !== "Y")
	{
		$arSystemTabs[$arTab["DIV"]] = $arTab["TAB"];
	}
}

$arSystemFields = array();
foreach($this->arSystemTabs as $arTab)
{
	if(!array_key_exists("CUSTOM", $arTab) || $arTab["CUSTOM"] !== "Y")
	{
		if(is_array($arTab["FIELDS"]))
		{
			foreach($arTab["FIELDS"] as $arField)
			{
				$id = htmlspecialcharsbx($arField["id"]);
				$label = htmlspecialcharsbx(rtrim(trim($arField["content"]), " :"));
				if($arField["delimiter"])
					$arSystemFields[$id] = "--".$label;
				else
					$arSystemFields[$id] = ($arField["required"]? "*": "&nbsp;&nbsp;").$label;
			}
		}
	}
}

$arAvailableTabs = $arSystemTabs;
$arAvailableFields = $arSystemFields;

$arCustomFields = array();
foreach($this->tabs as $arTab)
{
	if(!array_key_exists("CUSTOM", $arTab) || $arTab["CUSTOM"] !== "Y")
	{
		$ar = array(
			"TAB" => $arTab["TAB"],
			"FIELDS" => array(),
		);
		if(is_array($arTab["FIELDS"]))
		{
			foreach($arTab["FIELDS"] as $arField)
			{
				$id = htmlspecialcharsbx($arField["id"]);
				$label = htmlspecialcharsbx(rtrim(trim($arField["content"]), " :"));
				if($arField["delimiter"])
					$ar["FIELDS"][$id] = "--".$label;
				else
					$ar["FIELDS"][$id] = ($arField["required"]? "*": "&nbsp;&nbsp;").$label;
				unset($arAvailableFields[$id]);
			}
		}
		$arCustomFields[$arTab["DIV"]] = $ar;
		unset($arAvailableTabs[$arTab["DIV"]]);
	}
}

$arFormEditMess = array(
	"admin_lib_sett_tab_prompt" => GetMessage("admin_lib_sett_tab_prompt"),
	"admin_lib_sett_tab_default_name" => GetMessage("admin_lib_sett_tab_default_name"),
	"admin_lib_sett_sec_prompt" => GetMessage("admin_lib_sett_sec_prompt"),
	"admin_lib_sett_sec_default_name" => GetMessage("admin_lib_sett_sec_default_name"),
	"admin_lib_sett_sec_rename" => GetMessage("admin_lib_sett_sec_rename"),
	"admin_lib_sett_tab_rename" => GetMessage("admin_lib_sett_tab_rename"),
);

$obJSPopup = new CJSPopup(GetMessage("admin_lib_sett_tab_title"));
$obJSPopup->ShowTitlebar(GetMessage("admin_lib_sett_tab_title"));
$obJSPopup->StartContent();
?>
<script type="text/javascript">
var arSystemTabsFields = <?echo CUtil::PhpToJSObject($arSystemTabsFields)?>;
var arSystemTabs = <?echo CUtil::PhpToJSObject($arSystemTabs)?>;
var arSystemFields = <?echo CUtil::PhpToJSObject($arSystemFields)?>;
var arFormEditMess = <?echo CUtil::PhpToJSObject($arFormEditMess)?>;
(BX.defer(Sync))();
</script>
</form>
<form enctype="multipart/form-data" name="form_settings" action="<?echo $APPLICATION->GetCurPageParam()?>" method="POST">
<div class="settings-form">
<h2 ondblclick="exportSettingsToPhp(event, '<?echo $this->name;?>')"><?echo GetMessage("admin_lib_sett_tab_fields")?></h2>
<table width="100%" cellspacing="0">
	<tr valign="center">
		<td colspan="2"><?echo GetMessage("admin_lib_sett_tab_available_tabs")?>:</td>
		<td colspan="2"><?echo GetMessage("admin_lib_sett_tab_selected_tabs")?>:</td>
	</tr>
	<tr valign="center">
		<td width="0">
			<select class="select" name="available_tabs" id="available_tabs" onchange="Sync();" size="8" style="height: 190px;">
<?
foreach($arSystemTabs as $id => $label)
{
	echo '<option value="'.htmlspecialcharsbx($id).'">'.htmlspecialcharsbx($label).'</option>';
}
?>
			</select>
		</td>
		<td width="50%" align="center">
			<input type="button" name="tabs_copy" id="tabs_copy" value="&nbsp; &gt; &nbsp;" title="<?echo GetMessage("admin_lib_sett_tab_copy")?>" disabled onclick="OnAdd(this.id, <? echo $jsAdminFormParams; ?>);">
		</td>
		<td width="0">
			<select class="select" name="selected_tabs" id="selected_tabs" size="8" onchange="Sync();" style="height: 190px;">
<?
foreach($arCustomFields as $tab_id => $arTab)
{
	echo '<option value="'.htmlspecialcharsbx($tab_id).'">'.htmlspecialcharsbx($arTab["TAB"]).'</option>';
}
?>
			</select>
		</td>
		<td width="50%" align="center">
			<input type="button" name="tabs_up" id="tabs_up" class="button" value="<?echo GetMessage("admin_lib_sett_up")?>" title="<?echo GetMessage("admin_lib_sett_up_title")?>" disabled onclick="BX.selectUtils.moveOptionsUp(document.form_settings.selected_tabs);"><br>
			<input type="button" name="tabs_down" id="tabs_down" class="button" value="<?echo GetMessage("admin_lib_sett_down")?>" title="<?echo GetMessage("admin_lib_sett_down_title")?>" disabled onclick="BX.selectUtils.moveOptionsDown(document.form_settings.selected_tabs);"><br>
			<input type="button" name="tabs_rename" id="tabs_rename" class="button" value="<?echo GetMessage("admin_lib_sett_tab_rename")?>" title="<?echo GetMessage("admin_lib_sett_tab_rename_title")?>" disabled onclick="OnRename(this.id);"><br>
			<input type="button" name="tabs_add" id="tabs_add" class="button" value="<?echo GetMessage("admin_lib_sett_tab_add")?>" title="<?echo GetMessage("admin_lib_sett_tab_add_title")?>" onclick="OnAdd(this.id, <? echo $jsAdminFormParams; ?>);"><br>
			<input type="button" name="tabs_delete" id="tabs_delete" class="button" value="<?echo GetMessage("admin_lib_sett_del")?>" title="<?echo GetMessage("admin_lib_sett_del_title")?>" disabled onclick="OnDelete(this.id);"><br>
		</td>
	</tr>
	<tr valign="center">
		<td colspan="2"><?echo GetMessage("admin_lib_sett_tab_available_fields")?>:</td>
		<td colspan="2"><?echo GetMessage("admin_lib_sett_tab_selected_fields")?>:</td>
	</tr>
	<tr valign="center">
		<td>
			<select class="select" name="available_fields" id="available_fields" size="12" multiple onchange="Sync();" style="height: 255px;">
<?
foreach($arAvailableFields as $id => $label)
{
	echo '<option value="'.$id.'">'.$label.'</option>';
}
?>
			</select>
		</td>
		<td align="center">
			<input type="button" name="fields_copy" id="fields_copy" value="&nbsp; &gt; &nbsp;" title="<?echo GetMessage("admin_lib_sett_fields_copy")?>" disabled onclick="OnAdd(this.id, <? echo $jsAdminFormParams; ?>);"><br><br>
		</td>
		<td id="selected_fields">
			<select style="display:block; height: 255px;" disabled class="select" name="selected_fields[undef]" id="selected_fields[undef]" size="12" multiple></select>
<?
foreach($arCustomFields as $tab_id => $arTab)
{
	if(is_array($arTab["FIELDS"]))
	{
		echo '<select style="display:none; height:255px;" class="select" name="selected_fields['.$tab_id.']" id="selected_fields['.$tab_id.']" size="12" multiple onchange="Sync();">';
		foreach($arTab["FIELDS"] as $field_id => $label)
		{
			echo '<option value="'.$field_id.'">'.$label.'</option>';
		}
		echo '</select>';
	}
}
?>
		</td>
		<td align="center">
			<input type="button" name="fields_up" id="fields_up" class="button" value="<?echo GetMessage("admin_lib_sett_up")?>" title="<?echo GetMessage("admin_lib_sett_up_title")?>" disabled onclick="FieldsUpAndDown('up');"><br>
			<input type="button" name="fields_down" id="fields_down" class="button" value="<?echo GetMessage("admin_lib_sett_down")?>" title="<?echo GetMessage("admin_lib_sett_down_title")?>" disabled onclick="FieldsUpAndDown('down');"><br>
			<input type="button" name="fields_rename" id="fields_rename" class="button" value="<?echo GetMessage("admin_lib_sett_field_rename")?>" title="<?echo GetMessage("admin_lib_sett_field_rename_title")?>" disabled onclick="OnRename(this.id);"><br>
			<input type="button" name="fields_add" id="fields_add" class="button" value="<?echo GetMessage("admin_lib_sett_field_add")?>" title="<?echo GetMessage("admin_lib_sett_field_add_title")?>" onclick="OnAdd(this.id, <? echo $jsAdminFormParams; ?>);"><br>
			<input type="button" name="fields_delete" id="fields_delete" class="button" value="<?echo GetMessage("admin_lib_sett_del")?>" title="<?echo GetMessage("admin_lib_sett_fields_delete")?>" disabled onclick="OnDelete(this.id);">
		</td>
	</tr>
</table>
<?
if($GLOBALS["USER"]->CanDoOperation('edit_other_settings')):
?>
<h2><?echo GetMessage("admin_lib_sett_common")?></h2>
<table cellspacing="0" width="100%">
	<tr>
		<td><input type="checkbox" name="set_default" id="set_default" value="Y"></td>
		<td><label for="set_default"><?echo GetMessage("admin_lib_sett_common_set")?></label></td>
		<td><a class="delete-icon" title="<?echo GetMessage("admin_lib_sett_common_del")?>" href="javascript:if(confirm('<?echo GetMessage("admin_lib_sett_common_del_conf")?>'))<?echo $this->name?>.DeleteSettings(true)"></a></td>
	</tr>
</table>
<?
endif
?>
	<div id="save_settings_error" class="settings-error">
		<p class="settings-error-header"><?=GetMessage('SAVE_SETTINGS_ERROR_TITLE'); ?></p>
		<p class="settings-error-message"><?=GetMessage('SAVE_SETTINGS_ERROR'); ?></p>
		<div id="absent_required_fields" class="absent-fields"></div>
	</div>
</div>
</form>
<?
$obJSPopup->StartButtons();
?>
<input type="button" id="save_settings" value="<?echo GetMessage("admin_lib_sett_save")?>" onclick="<?echo $this->name?>.SaveSettings(this);" title="<?echo GetMessage("admin_lib_sett_save_title")?>" class="adm-btn-save">
<input type="button" value="<?echo GetMessage("admin_lib_sett_cancel")?>" onclick="<?echo $this->name?>.CloseSettings()" title="<?echo GetMessage("admin_lib_sett_cancel_title")?>">
<input type="button" value="<?echo GetMessage("admin_lib_sett_reset")?>" onclick="if(confirm('<?echo GetMessage("admin_lib_sett_reset_ask")?>'))<?echo $this->name?>.DeleteSettings()" title="<?echo GetMessage("admin_lib_sett_reset_title")?>">
<?
$obJSPopup->EndButtons();
?>settings_admin_list.php000064400000012704147732346240011340 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

if($this->sort)
{
	if(empty($aOptions["by"]))
		$aOptions["by"] = $this->sort->by_initial;
	if(empty($aOptions["order"]))
		$aOptions["order"] = $this->sort->order_initial;
}
if(intval($aOptions["page_size"]) <= 0)
{
	$aOptions["page_size"] = 20;
}

$obJSPopup = new CJSPopup(GetMessage("admin_lib_sett_title"));
$obJSPopup->ShowTitlebar();
$obJSPopup->StartContent();
echo '</form>';
?>
<div class="settings-form">
<form name="list_settings">
<h2><?=GetMessage("admin_lib_sett_cols")?></h2>
<table cellspacing="0" width="100%">
	<tr>
		<td colspan="2"><?=GetMessage("admin_lib_sett_all")?></td>
		<td colspan="2"><?=GetMessage("admin_lib_sett_sel")?></td>
	</tr>
	<tr>
		<td width="0">
			<select class="select" name="all_columns" id="list_settings_all_columns" size="10" multiple onchange="document.list_settings.add.disabled=(this.selectedIndex == -1);">
<?
$bNeedSort = false;
foreach($aAllCols as $header)
{
	echo '<option value="'.$header["id"].'">'.($header["name"]<>""? $header["name"]:$header["content"]).'</option>';
	if($header["sort"] <> "")
	{
		$bNeedSort = true;
	}
}
?>
			</select>
		</td>
		<td align="center" width="50%"><input type="button" name="add" value="&nbsp; &gt; &nbsp;" title="<?=GetMessage("admin_lib_sett_sel_title")?>" disabled onclick="BX.selectUtils.addSelectedOptions(document.list_settings.all_columns, 'list_settings_selected_columns');"></td>
		<td width="0">
			<select class="select" name="selected_columns" id="list_settings_selected_columns" size="10" multiple onchange="var frm=document.list_settings; frm.up.disabled=frm.down.disabled=frm.del.disabled=(this.selectedIndex == -1);">
<?
$bEmptyCols = empty($aCols);
foreach($this->aHeaders as $header)
{
	if(($bEmptyCols && $header["default"]==true) || in_array($header["id"], $aCols))
	{
		echo '<option value="'.$header["id"].'">'.($header["name"]<>""? $header["name"]:$header["content"]).'</option>';
	}
}
?>
			</select>
		</td>
		<td align="center" width="50%">
			<input type="button" name="up" class="button" value="<?=GetMessage("admin_lib_sett_up")?>" title="<?=GetMessage("admin_lib_sett_up_title")?>" disabled="disabled" onclick="BX.selectUtils.moveOptionsUp(document.list_settings.selected_columns);" /><br />
			<input type="button" name="down" class="button" value="<?=GetMessage("admin_lib_sett_down")?>" title="<?=GetMessage("admin_lib_sett_down_title")?>" disabled="disabled" onclick="BX.selectUtils.moveOptionsDown(document.list_settings.selected_columns);" /><br />
			<input type="button" name="del" class="button" value="<?=GetMessage("admin_lib_sett_del")?>" title="<?=GetMessage("admin_lib_sett_del_title")?>" disabled="disbled" onclick="BX.selectUtils.deleteSelectedOptions('list_settings_selected_columns'); document.list_settings.selected_columns.onchange();" /><br />
		</td>
	</tr>
</table>
<h2><?=GetMessage("admin_lib_sett_def_title")?></h2>
<table cellspacing="0" width="100%">
<?
if($this->sort && $bNeedSort)
{
?>
	<tr>
		<td align="right"><?=GetMessage("admin_lib_sett_sort")?></td>
		<td>
			<select name="order_field">
<?
	$by = strtoupper($aOptions["by"]);
	$order = strtoupper($aOptions["order"]);
	foreach($aAllCols as $header)
	{
		if($header["sort"] <> "")
		{
			echo '<option value="'.$header["sort"].'"'.($by == strtoupper($header["sort"])? ' selected':'').'>'.($header["name"]<>""? $header["name"]:$header["content"]).'</option>';
		}
	}
?>
			</select>
			<select name="order_direction">
				<option value="desc"<?=($order == "DESC"? ' selected':'')?>><?=GetMessage("admin_lib_sett_desc")?></option>
				<option value="asc"<?=($order == "ASC"? ' selected':'')?>><?=GetMessage("admin_lib_sett_asc")?></option>
			</select>
		</td>
	</tr>
<?
} // if($this->sort && $bNeedSort)
?>
	<tr>
		<td align="right"><?=GetMessage("admin_lib_sett_rec")?></td>
		<td>
			<select name="nav_page_size">
<?
$aSizes = array(10, 20, 50, 100, 200, 500);
foreach($aSizes as $size)
{
	echo '<option value="'.$size.'"'.($aOptions["page_size"] == $size? ' selected':'').'>'.$size.'</option>';
}
?>
			</select>
		</td>
	</tr>
</table>
<?
if($USER->CanDoOperation('edit_other_settings'))
{
?>
<h2><?=GetMessage("admin_lib_sett_common")?></h2>
<table cellspacing="0" width="100%">
	<tr>
		<td><input type="checkbox" name="set_default" id="set_default" value="Y"></td>
		<td><label for="set_default"><?=GetMessage("admin_lib_sett_common_set")?></label></td>
		<td><a class="delete-icon" title="<?=GetMessage("admin_lib_sett_common_del")?>" href="javascript:if(confirm('<?=CUtil::JSEscape(GetMessage("admin_lib_sett_common_del_conf"))?>'))<?=$this->table_id?>.DeleteSettings(true)"></a></td>
	</tr>
</table>
<?
} //if($USER->CanDoOperation('edit_other_settings'))
?>
</form>
</div>
<script type="text/javascript">
BX.adminFormTools.modifyFormElements('list_settings')
</script>
<?
$obJSPopup->StartButtons();
?>
<input class="adm-btn-save" type="button" value="<?=GetMessage("admin_lib_sett_save")?>" onclick="<?=$this->table_id?>.SaveSettings(this)" title="<?=GetMessage("admin_lib_sett_save_title")?>" />
<input type="button" value="<?=GetMessage("admin_lib_sett_cancel")?>" onclick="BX.WindowManager.Get().Close()" title="<?=GetMessage("admin_lib_sett_cancel_title")?>" />
<input type="button" value="<?=GetMessage("admin_lib_sett_reset")?>" onclick="if(confirm('<?=CUtil::JSEscape(GetMessage("admin_lib_sett_reset_ask"))?>'))<?=$this->table_id?>.DeleteSettings()" title="<?=GetMessage("admin_lib_sett_reset_title")?>" />
<?
$obJSPopup->EndButtons();
?>admin_styles.min.css000064400000014126147732346240010553 0ustar00body{margin:0;padding:0}a:hover{color:red}.navchain{font-family:Arial;font-size:12px;color:#1f5887}hr.tinygrey{color:#dedede;height:1px}.leftmenu,.leftmenuact,.leftmenusep{font-family:Arial;font-size:9pt;font-weight:normal;text-decoration:none}.leftmenu{color:#556877}.leftmenuact{color:#f8270a}.leftmenusep{color:#436287}.leftmenusepbg{background-color:#dbe9f3}.leftmenusepdelim{background-color:#b9d3e6}.leftmenubg{background-color:#f3f3f3}.hiddenmenu{font-family:Tahoma,Arial,sans-serif;color:#556877;font-size:12px;padding-top:8px;cursor:pointer;line-height:11px}.floatmenu{border:solid 1px #82b0d2;background-color:#f3f3f3;padding:5px;line-height:18px}a.leftmenu:hover{text-decoration:underline;color:#556877}a.leftmenuact:hover{text-decoration:underline;color:#f8270a}a.leftmenusep:hover{color:#436287}.tablehead,.tablehead1,.tablehead2,.tablehead3,.tablehead4,.tablehead5,.tableheadbottom,.tableheadtop{background-color:#c2dbed;padding:3px}.tablehead1,.tablehead2,.tablehead3{border-top:1px solid #a8c2d7;border-bottom:1px solid #a8c2d7}.tablehead1,.tableheadleft{border-left:1px solid #a8c2d7}.tablehead3,.tableheadright{border-right:1px solid #a8c2d7}.tablehead4,.tablehead5{border-bottom:1px solid #a8c2d7;border-left:1px solid #a8c2d7;border-right:1px solid #a8c2d7}.tablehead5,.tableheadtop{border-top:1px solid #a8c2d7}.tableheadbottom{border-bottom:1px solid #a8c2d7}.tablebody,.tablebody1,.tablebody2,.tablebody3,.tablebody4,.tablebody5,.tablebodyleft,.tablebodyright,.tablebodytop,.tablebodybottom{background-color:#f1f1f1;padding:3px}.tablebody1{border-left:#ced6db solid 1px;border-bottom:#ced6db solid 1px}.tablebody2,.tablebodybottom{border-bottom:#ced6db solid 1px}.tablebody3{border-right:#ced6db solid 1px;border-bottom:#ced6db solid 1px}.tablebody4,.tablebody5{border-right:#ced6db solid 1px;border-left:#ced6db solid 1px;border-bottom:#ced6db solid 1px}.tablebody5,.tablebodytop{border-top:#ced6db solid 1px}.tablebodyleft{border-left:#ced6db solid 1px}.tablebodyright{border-right:#ced6db solid 1px}.selectedbody{background-color:#e0ebf1}.tablenullbody{background-color:#fff}.edittable{border:#a9c9e0 1px solid}.edittable td{background-color:#f1f1f1;padding:4px}.edittable .tablehead{background-color:#e4edf3;padding:4px}.edittable .selectedbody{background-color:#e9e9e9}.edittable .tableheadtext{color:#365069}.smallpadding td{padding:1px}.nopadding td{padding:0}.tableborder{background-color:#8bb6d6}.border{border:#a9c9e0 1px solid}.filter{border:1px solid #c2dbed;border-top:0}.tablefilterhead{background-color:#c2dbed;padding:3px}table.filter .tablebody{background-color:#f3f3f3;padding:3px}.tablebodytext,.tableheadtext,.tablefieldtext,.tabletitletext{font-family:Arial;font-size:12px}.tableheadtext,.tablebodytext,.tabletitletext{color:#000}.tablefieldtext{color:#365069}.actions{line-height:14px}.notesmall,.note,.attention,.attentionsmall{font-family:Arial;font-weight:normal}.notesmall{font-size:11px;color:#000}.note{font-size:12px;color:#000}.attention{font-size:12px;color:red}.attentionsmall{font-size:11px;color:red}.tablehead .notesmall,.tablehead1 .notesmall,.tablehead2 .notesmall,.tablehead3 .notesmall,.tablehead4 .notesmall,.tableheadbottom .notesmall,.tableheadtop .notesmall,.tableheadleft .notesmall,.tableheadright .notesmall,.selectedbody .notesmall,{color:green}.tablebody .note,.tablebody1 .note,.tablebody2 .note,.tablebody3 .note,.tablebody4 .note{color:green}a.txttohtmllink{text-decoration:none}a.txttohtmllink:hover{text-decoration:underline;color:red}a.tablebodylink{font-family:Arial;font-size:12px;text-decoration:none;color:#0167cd}.tablehead a.tablebodylink{color:#295576}a.tablebodylink:hover{text-decoration:underline;color:red}.text,.smalltext,.smalltextlink{font-family:Arial;font-weight:normal}.text{font-size:12px;color:#000}.smalltext{font-size:11px;color:#000}.smalltextlink{font-size:11px;text-decoration:none}a.smalltextlink:hover{text-decoration:underline}a.smalltext:hover{color:#000}.notetable{background-color:#ffffec}.legendtext{font-family:Arial;font-size:11px;color:#000;font-weight:normal}.star,.starrequired{font-family:Verdana;font-size:8pt}.starrequired{color:#f00}.submenutable{background-color:#ffffec}.submenutext{font-family:Arial;font-size:9pt;font-weight:normal;color:#4d5f6c;text-decoration:none}a.submenutext:hover{text-decoration:underline;color:#4d5f6c}.justify{text-align:justify}.linktext{font-family:Verdana;font-size:10pt;color:#000;font-weight:normal}.textmain{font-family:Verdana;font-size:12px;line-height:15px;text-decoration:none}.textb{font-family:Arial;font-size:10pt;color:#000;font-weight:bold}.subtitletext{font-family:Arial;color:#000;font-size:11pt;font-weight:bold}.smalltxt,.smalltxtw,.smalltxtws{font-family:Verdana;text-decoration:none}.smalltxt{font-size:11px;line-height:13px}.smalltxtw{font-size:10px;line-height:12px;color:#696c72}.smalltxtws{font-size:10px;line-height:12px;color:#ff7979}a.smalltxtw:hover{text-decoration:underline}a.smalltxtws:hover{text-decoration:underline}.tableheads{background-color:#e4e6db}.tableborders{background-color:#9c9a9c}.errortext,.oktext,.notetext{font-family:Arial;font-size:10pt;font-weight:bold}.errortext{color:red}.oktext{color:#005000}.notetext{color:green}.required{color:red}.pointed{color:green}.pointed2{color:blue}form{margin-top:16px;margin-bottom:16px}.filter form{margin:0}INPUT.typeinput,INPUT.typefile,TEXTAREA.typearea,SELECT.typeselect{background-color:#fff;font-size:12px;font-family:Arial}INPUT.button{padding:2px;font-family:Tahoma;font-size:12px;color:#fff;background-color:#6aa2ca;border:2px solid #4083b5;cursor:pointer}.tablebodybutton{font-size:12px;font-family:Arial}.textareawidth{width:90%}.titlemenu{font-family:Arial,sans-serif;font-size:12px}.titlemenuselected{color:#9b1704}.pagetitle{background-color:#fff;border-bottom:1px solid #beceee;padding:3px;padding-left:0;padding-right:0}.titletext{font-family:Arial;color:#000;font-weight:bold;font-size:17px}.pagesubtitle{background-color:#ebebeb;padding:3px;margin-top:32px;margin-bottom:16px}.h2{font-family:Tahoma;font-size:13px;font-weight:bold;color:#000}.pagebottom{background-color:#eee;border-top:1px solid #dbdbdb;padding:5px}.pagebottomtext{font-family:Tahoma;font-size:11px;color:black}admin_form.php000064400000075457147732346240007426 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

class CAdminForm extends CAdminTabControl
{
	var $arParams = array();
	var $arFields = array();
	var $arForbiddenFields = array();
	var $group = "";
	var $group_ajax = false;
	var $arFieldValues = array();
	var $sPrologContent = "";
	var $sEpilogContent = "";
	var $arButtonsParams = false;
	var $sButtonsContent = "";

	var $arSavedTabs = array();
	var $arSystemTabs = array();
	var $arSystemFields = array();
	var $arReqiredTabs = array();

	var $arCustomLabels = array();
	var $bCustomFields = false;
	var $sCurrentLabel = "";
	var $bCurrentReq = false;

	var $bShowSettings = true;

	public function __construct($name, $tabs, $bCanExpand = true, $bDenyAutosave = false)
	{
		parent::__construct($name, $tabs, $bCanExpand, $bDenyAutosave);
		$this->tabIndex = 0;
		foreach($this->tabs as $i => $arTab)
			$this->tabs[$i]["FIELDS"] = array();

		//Parse customized labels
		$this->arCustomLabels = array();

		$arDisabled = CUserOptions::GetOption("form", $this->name."_disabled", "N");
		if(!is_array($arDisabled) || $arDisabled["disabled"] !== "Y")
		{
			foreach (CAdminFormSettings::getTabsArray($this->name) as $arTab)
			{
				foreach ($arTab["FIELDS"] as $customID => $customName)
				{
					$this->arCustomLabels[$customID] = $customName;
				}
			}
		}
		ob_start();
	}

	/** @deprecated */
	public function CAdminForm($name, $tabs, $bCanExpand = true, $bDenyAutosave = false)
	{
		self::__construct($name, $tabs, $bCanExpand, $bDenyAutosave);
	}

	function SetSelectedTab()
	{
		parent::SetSelectedTab();

		$arDisabled = CUserOptions::GetOption("form", $this->name."_disabled", "N");
		if(!is_array($arDisabled) || $arDisabled["disabled"] !== "Y")
		{
			if(isset($_REQUEST[$this->name."_active_tab"]))
			{
				$arCustomTabs = CAdminFormSettings::getTabsArray($this->name);
				foreach($arCustomTabs as $tab_id => $arTab)
				{
					if($tab_id == $_REQUEST[$this->name."_active_tab"])
					{
						$this->selectedTab = $_REQUEST[$this->name."_active_tab"];
						break;
					}
				}
			}
		}
	}

	function SetShowSettings($v)
	{
		$this->bShowSettings = $v;
	}

	function ShowSettings()
	{
		/** @noinspection PhpUnusedLocalVariableInspection */
		/** @global CMain $APPLICATION */
		global $APPLICATION, $USER;

		$APPLICATION->RestartBuffer();

		require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_js.php");

		require($_SERVER['DOCUMENT_ROOT']."/bitrix/modules/main/interface/settings_admin_form.php");

		require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin_js.php");

		die();
	}

	function SetFieldsValues($bVarsFromForm, $db_record, $default_values)
	{
		foreach($default_values as $key=>$value)
			$this->SetFieldValue($key, $bVarsFromForm, $db_record, $value);
	}

	function SetFieldValue($field_name, $bVarsFromForm, $db_record, $default_value = false)
	{
		if($bVarsFromForm)
		{
			if(array_key_exists($field_name, $_REQUEST))
				$this->arFieldValues[$field_name] = $_REQUEST[$field_name];
			else
				$this->arFieldValues[$field_name] = $default_value;
		}
		else
		{
			if(is_array($db_record) && array_key_exists($field_name, $db_record) && isset($db_record[$field_name]))
				$this->arFieldValues[$field_name] = $db_record[$field_name];
			else
				$this->arFieldValues[$field_name] = $default_value;
		}
	}

	function GetFieldValue($field_name)
	{
		return $this->arFieldValues[$field_name];
	}

	function GetHTMLFieldValue($field_name)
	{
		return htmlspecialcharsbx($this->arFieldValues[$field_name]);
	}

	function GetHTMLFieldValueEx($field_name)
	{
		return htmlspecialcharsex($this->arFieldValues[$field_name]);
	}

	function GetFieldLabel($id)
	{
		return $this->arFields[$id]["content"];
	}

	function ShowTabButtons()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		$s = '';
		if (!$this->bPublicMode)
		{
			if ($this->bShowSettings)
			{
				$link = DeleteParam(array("mode"));
				$link = $APPLICATION->GetCurPage()."?mode=settings".($link <> ""? "&".$link:"");

				$aAdditionalMenu = array();

				$aAdditionalMenu[] = array(
					"TEXT"=>GetMessage("admin_lib_menu_settings"),
					"TITLE"=>GetMessage("admin_lib_context_sett_title"),
					"ONCLICK"=>$this->name.".ShowSettings('".htmlspecialcharsbx(CUtil::JSEscape($link))."')",
					"GLOBAL_ICON"=>"adm-menu-setting"
				);

				if($this->bCustomFields)
				{
					if(is_array($_SESSION["ADMIN_CUSTOM_FIELDS"]) && array_key_exists($this->name, $_SESSION["ADMIN_CUSTOM_FIELDS"]))
					{
						$aAdditionalMenu[] = array(
							"TEXT" => GetMessage("admin_lib_sett_sett_enable_text"),
							"TITLE" => GetMessage("admin_lib_sett_sett_enable"),
							"ONCLICK" => $this->name.'.EnableSettings();',
							"ICON" => 'custom-fields-on',
						);
					}
					else
					{
						$aAdditionalMenu[] = array(
							"TEXT" => GetMessage("admin_lib_sett_sett_disable_text"),
							"TITLE" => GetMessage("admin_lib_sett_sett_disable"),
							"ONCLICK" => $this->name.'.DisableSettings();',
							"ICON" => 'custom-fields-off'
						);

					}
				}

				if (count($aAdditionalMenu) > 1)
				{
					$sMenuUrl = "BX.adminShowMenu(this, ".htmlspecialcharsbx(CAdminPopup::PhpToJavaScript($aAdditionalMenu)).", {active_class: 'bx-settings-btn-active'});";
					$bCustomFieldsOff = is_array($_SESSION["ADMIN_CUSTOM_FIELDS"]) && array_key_exists($this->name, $_SESSION["ADMIN_CUSTOM_FIELDS"]);

					$s .= '<span id="'.$this->name.'_settings_btn" class="adm-detail-settings adm-detail-settings-arrow'.($bCustomFieldsOff ? '' : ' adm-detail-settings-active').'" onclick="'.$sMenuUrl.'"></span>';
				}
				else
				{
					$s .= '<a class="adm-detail-settings" href="javascript:void(0)" onclick="'.$aAdditionalMenu[0]['ONCLICK'].'"></a>';
				}
			}
		}

		return $s.parent::ShowTabButtons();
	}

	function Begin($arParams = array())
	{
		$this->tabIndex = -1;
		if(is_array($arParams))
			$this->arParams = $arParams;
		else
			$this->arParams = array();
	}

	function BeginNextFormTab()
	{
		if($this->tabIndex >= count($this->tabs))
			return;

		$this->tabIndex++;
		while(
			isset($this->tabs[$this->tabIndex])
			&& array_key_exists("CUSTOM", $this->tabs[$this->tabIndex])
			&& $this->tabs[$this->tabIndex]["CUSTOM"] == "Y"
		)
		{
			ob_start();
			$this->customTabber->ShowTab($this->tabs[$this->tabIndex]["DIV"]);
			$this->tabs[$this->tabIndex]["required"] = true;
			$this->tabs[$this->tabIndex]["CONTENT"] = ob_get_contents();
			ob_end_clean();
			$this->tabIndex++;
		}
	}

	function Show()
	{
		/** @global CMain $APPLICATION */
		global $APPLICATION;

		//Save form defined tabs
		$this->arSavedTabs = $this->tabs;
		$this->arSystemTabs = array();
		$this->arReqiredTabs = array();

		foreach($this->tabs as $arTab)
		{
			$this->arSystemTabs[$arTab["DIV"]] = $arTab;

			if(is_array($arTab["FIELDS"]))
			{
				foreach($arTab["FIELDS"] as $arField)
					$this->arFields[$arField["id"]] = $arField;
			}

			if (
				$arTab["required"]
				&& (
					is_array($arTab["FIELDS"])
					|| isset($arTab["CONTENT"])
				)
			)
			{
				$this->arReqiredTabs[$arTab["DIV"]] = $arTab;
			}
		}
		//Save form defined fields
		$this->arSystemFields = $this->arFields;

		$arCustomTabs = CAdminFormSettings::getTabsArray($this->name);
		if (!empty($arCustomTabs))
		{
			$this->bCustomFields = true;
			$this->tabs = array();
			foreach($arCustomTabs as $tab_id => $arTab)
			{
				if(array_key_exists($tab_id, $this->arSystemTabs))
				{
					$arNewTab = $this->arSystemTabs[$tab_id];
					$arNewTab["TAB"] = $arTab["TAB"];
					$arNewTab["FIELDS"] = array();
				}
				else
				{
					$arNewTab = array(
						"DIV" => $tab_id,
						"TAB" => $arTab["TAB"],
						"ICON" => "main_user_edit",
						"TITLE" => "",
						"FIELDS" => array(),
					);
				}

				$bHasFields = false;
				foreach($arTab["FIELDS"] as $field_id => $content)
				{
					if(array_key_exists($field_id, $this->arSystemFields))
					{
						$arNewField = $this->arSystemFields[$field_id];
						$arNewField["content"] = $content;
						$bHasFields = true;
					}
					elseif(array_key_exists($field_id, $this->arForbiddenFields))
					{
						$arNewField = false;
					}
					elseif(strlen($content) > 0)
					{
						$arNewField = array(
							"id" => $field_id,
							"content" => $content,
							"html" => '<td colspan="2">'.htmlspecialcharsex($content).'</td>',
							"delimiter" => true,
						);
					}
					else
					{
						$arNewField = false;
					}

					if(is_array($arNewField))
					{
						$this->arFields[$field_id] = $arNewField;
						$arNewTab["FIELDS"][] = $arNewField;
						foreach ($this->arReqiredTabs as $tab_id => $arReqTab)
						{
							if (is_array($arReqTab["FIELDS"]))
							{
								foreach ($arReqTab["FIELDS"] as $i => $arReqTabField)
								{
									if ($arReqTabField["id"] == $field_id)
										unset($this->arReqiredTabs[$tab_id]["FIELDS"][$i]);
								}
							}
						}
					}
				}

				if ($bHasFields)
					$this->tabs[] = $arNewTab;
			}

			foreach ($this->arReqiredTabs as $arReqTab)
			{
				if (!empty($arReqTab["FIELDS"]))
				{
					$this->tabs[] = $arReqTab;
					foreach ($arReqTab["FIELDS"] as $arReqTabField)
					{
						$this->arFields[$arReqTabField["id"]] = $arReqTabField;
					}
				}
				elseif (isset($arReqTab["CONTENT"]))
				{
					$this->tabs[] = $arReqTab;
				}
			}
		}

		if($_REQUEST["mode"] == "settings")
		{
			ob_end_clean();
			$this->ShowSettings($this->arFields);
			die();
		}
		else
		{
			ob_end_flush();
		}

		if(!is_array($_SESSION["ADMIN_CUSTOM_FIELDS"]))
			$_SESSION["ADMIN_CUSTOM_FIELDS"] = array();
		$arDisabled = CUserOptions::GetOption("form", $this->name."_disabled", "N");
		if(is_array($arDisabled) && $arDisabled["disabled"] === "Y")
		{
			$_SESSION["ADMIN_CUSTOM_FIELDS"][$this->name] = true;
			$this->tabs = $this->arSavedTabs;
			$this->arFields = $this->arSystemFields;
		}
		else
		{
			unset($_SESSION["ADMIN_CUSTOM_FIELDS"][$this->name]);
		}

		if(isset($_REQUEST[$this->name."_active_tab"]))
			$this->selectedTab = $_REQUEST[$this->name."_active_tab"];
		else
			$this->selectedTab = $this->tabs[0]["DIV"];

		//To show
		$arHiddens = $this->arFields;
		echo $this->sPrologContent;
		if(array_key_exists("FORM_ACTION", $this->arParams))
			$action = htmlspecialcharsbx($this->arParams["FORM_ACTION"]);
		else
			$action = htmlspecialcharsbx($APPLICATION->GetCurPage());
		echo '<form method="POST" action="'.$action.'"  enctype="multipart/form-data" id="'.$this->name.'_form" name="'.$this->name.'_form"'.($this->arParams["FORM_ATTRIBUTES"] <> ''? ' '.$this->arParams["FORM_ATTRIBUTES"]:'').'>';

		$htmlGroup = "";
		if($this->group)
		{
			if (!empty($arCustomTabs))
			{
				foreach($this->tabs as $arTab)
				{
					if(is_array($arTab["FIELDS"]))
					{
						foreach($arTab["FIELDS"] as $arField)
						{
							if(
								(strlen($this->arFields[$arField["id"]]["custom_html"]) > 0)
								|| (strlen($this->arFields[$arField["id"]]["html"]) > 0)
							)
							{
								$p = array_search($arField["id"], $this->arFields[$this->group]["group"]);
								if($p !== false)
									unset($this->arFields[$this->group]["group"][$p]);
							}
						}
					}
				}
			}

			if(!empty($this->arFields[$this->group]["group"]))
			{
				$htmlGroup .= '<tr class="heading" id="tr_'.$this->arFields[$this->group]["id"].'">'
					.$this->arFields[$this->group]["html"].'</tr>'
					."\n";
			}
		}

		$this->OnAdminTabControlBegin();
		$this->tabIndex = 0;
		while($this->tabIndex < count($this->tabs))
		{
			ob_start();//Start of the tab content
			$arTab = $this->tabs[$this->tabIndex];
			if(is_array($arTab["FIELDS"]))
			{
				foreach($arTab["FIELDS"] as $arField)
				{
					if(isset($this->arFields[$arField["id"]]["group"]))
					{
						if(!empty($this->arFields[$arField["id"]]["group"]))
						{
							echo $htmlGroup;
							foreach($this->arFields[$arField["id"]]["group"] as $p)
							{
								if($this->arFields[$p]["custom_html"])
									echo preg_replace("/^\\s*<tr/is", "<tr class=\"bx-in-group\"", $this->arFields[$p]["custom_html"]);
								elseif($this->arFields[$p]["html"] && !$this->arFields[$p]["delimiter"])
									echo '<tr class="bx-in-group" '.($this->arFields[$p]["valign"] <> ''? ' valign="'.$this->arFields[$p]["valign"].'"':'').' id="tr_'.$p.'">', $this->arFields[$p]["html"], "</tr>\n";
								unset($arHiddens[$this->arFields[$p]["id"]]);
								$this->arFields[$p] = array();
							}
						}
					}
					elseif(strlen($this->arFields[$arField["id"]]["custom_html"]) > 0)
					{
						if($this->group_ajax)
							echo preg_replace("#<script[^>]*>.*?</script>#im".BX_UTF_PCRE_MODIFIER, "", $this->arFields[$arField["id"]]["custom_html"]);
						else
							echo $this->arFields[$arField["id"]]["custom_html"];
					}
					elseif(strlen($this->arFields[$arField["id"]]["html"]) > 0)
					{
						$rowClass = (
							array_key_exists("rowClass", $this->arFields[$arField["id"]])
							? ' class="'.$this->arFields[$arField["id"]]["rowClass"].'"'
							: ''
						);

						if($this->arFields[$arField["id"]]["delimiter"])
							echo '<tr class="heading" id="tr_'.$arField["id"].'"'.$rowClass.'>';
						else
							echo '<tr'.($this->arFields[$arField["id"]]["valign"] <> ''? ' valign="'.$this->arFields[$arField["id"]]["valign"].'"':'').' id="tr_'.$arField["id"].'"'.$rowClass.'>';
						echo $this->arFields[$arField["id"]]["html"].'</tr>'."\n";
					}
					unset($arHiddens[$arField["id"]]);
				}
			}
			elseif (isset($arTab["CONTENT"]))
			{
				echo $arTab["CONTENT"];
			}
			$tabContent = ob_get_contents();
			ob_end_clean(); //Dispose tab content

			if ($tabContent == "")
			{
				array_splice($this->tabs, $this->tabIndex, 1); // forget about tab
			}
			else
			{

				$this->tabs[$this->tabIndex]["CONTENT"] = $tabContent;
				$this->tabIndex++;
			}
		}

		//sometimes form settings are incorrect but we must show required fields
		$requiredFields = '';
		foreach($arHiddens as $arField)
		{
			if($arField["required"])
			{
				if(strlen($this->arFields[$arField["id"]]["custom_html"]) > 0)
				{
					$requiredFields .= $this->arFields[$arField["id"]]["custom_html"];
				}
				elseif(strlen($this->arFields[$arField["id"]]["html"]) > 0)
				{
					if($this->arFields[$arField["id"]]["delimiter"])
						$requiredFields .= '<tr class="heading">';
					else
						$requiredFields .= '<tr>';
					$requiredFields .= $this->arFields[$arField["id"]]["html"].'</tr>';
				}
				unset($arHiddens[$arField["id"]]);
			}
		}
		if($requiredFields <> '')
		{
			$this->tabs[] = array(
				"CONTENT" => $requiredFields,
				"DIV" => "bx_req",
				"TAB" => GetMessage("admin_lib_required"),
				"TITLE" => GetMessage("admin_lib_required"),
			);
		}

		parent::Begin();

		while($this->tabIndex < count($this->tabs))
		{
			$this->BeginNextTab();
			echo $this->tabs[$this->tabIndex]["CONTENT"];
		}

		parent::Buttons($this->arButtonsParams);
		echo $this->sButtonsContent;

		$this->End();
		echo $this->sEpilogContent;

		echo '<span class="bx-fields-hidden">';
		foreach($arHiddens as $arField)
		{
			echo $arField["hidden"];
		}
		echo '</span>';

		echo '</form>';
	}

	function GetName()
	{
		return $this->name;
	}

	function GetFormName()
	{
		return $this->name."_form";
	}

	function GetCustomLabel($id, $content)
	{
		$bColumnNeeded = substr($content, -1)==":";

		if($id === false)
			return $this->sCurrentLabel;
		elseif(array_key_exists($id, $this->arCustomLabels))
			return $this->arCustomLabels[$id].($bColumnNeeded? ":": "");
		else
			return $content;
	}

	function GetCustomLabelHTML($id = false, $content = "")
	{
		$bColumnNeeded = substr($content, -1)==":";

		if($id === false)
			return ($this->bCurrentReq? '<span class="adm-required-field">'.htmlspecialcharsex($this->sCurrentLabel).'</span>': htmlspecialcharsex($this->sCurrentLabel));
		elseif(array_key_exists($id, $this->arCustomLabels))
			return ($this->arFields[$id]["required"]? '<span class="adm-required-field">'.htmlspecialcharsex($this->arCustomLabels[$id]).($bColumnNeeded? ":": "").'</span>': htmlspecialcharsex($this->arCustomLabels[$id]).($bColumnNeeded? ":": ""));
		else
			return ($this->tabs[$this->tabIndex]["FIELDS"][$id]["required"]? '<span class="adm-required-field">'.htmlspecialcharsex($content).'</span>': htmlspecialcharsex($content));
	}

	function ShowWarnings($form, $messages, $aFields=false)
	{
		parent::ShowWarnings($this->name.'_form', $messages, $aFields);
	}

	function BeginPrologContent()
	{
		ob_start();
	}

	function EndPrologContent()
	{
		$this->sPrologContent = ob_get_contents();
		ob_end_clean();
	}

	function BeginEpilogContent()
	{
		ob_start();
	}

	function EndEpilogContent()
	{
		$this->sEpilogContent = ob_get_contents();
		ob_end_clean();
	}

	function AddFieldGroup($id, $content, $arFields, $bAjax = false)
	{
		$this->group = $id;
		$this->group_ajax = $bAjax;
		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"content" => $content,
			"group" => $arFields,
			"html" => '<td colspan="2">'.$this->GetCustomLabelHTML($id, $content).'</td>',
		);
	}

	function HideField($id)
	{
		$this->arForbiddenFields[$id] = true;
	}

	function AddSection($id, $content, $required = false)
	{
		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"delimiter" => true,
			"content" => $content,
			"html" => '<td colspan="2">'.($required? '<span class="adm-required-field">'.$this->GetCustomLabelHTML($id, $content).'</span>': $this->GetCustomLabelHTML($id, $content)).'</td>',
		);
	}

	function AddViewField($id, $content, $html, $required=false)
	{
		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $content,
			"html" => ($html <> ''? '<td width="40%">'.$this->GetCustomLabelHTML($id, $content).'</td><td>'.$html.'</td>' : ''),
		);
	}

	function AddDropDownField($id, $content, $required, $arSelect, $value=false, $arParams=array())
	{
		if($value === false)
			$value = $this->arFieldValues[$id];

		$html = '<select name="'.$id.'"';
		foreach($arParams as $param)
			$html .= ' '.$param;
		$html .= '>';

		foreach($arSelect as $key => $val)
			$html .= '<option value="'.htmlspecialcharsbx($key).'"'.($value == $key? ' selected': '').'>'.htmlspecialcharsex($val).'</option>';
		$html .= '</select>';

		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $content,
			"html" => '<td width="40%">'.($required? '<span class="adm-required-field">'.$this->GetCustomLabelHTML($id, $content).'</span>': $this->GetCustomLabelHTML($id, $content)).'</td><td>'.$html.'</td>',
			"hidden" => '<input type="hidden" name="'.$id.'" value="'.htmlspecialcharsbx($value).'">',
		);
	}

	function AddEditField($id, $content, $required, $arParams = array(), $value = false)
	{
		if($value === false)
			$value = htmlspecialcharsbx($this->arFieldValues[$id]);
		else
			$value = htmlspecialcharsbx(htmlspecialcharsback($value));

		$html = '<input type="text" name="'.$id.'" value="'.$value.'"';
		if(intval($arParams["size"]) > 0)
			$html .= ' size="'.intval($arParams["size"]).'"';
		if(intval($arParams["maxlength"]) > 0)
			$html .= ' maxlength="'.intval($arParams["maxlength"]).'"';
		if($arParams["id"])
			$html .= ' id="'.htmlspecialcharsbx($arParams["id"]).'"';
		$html .= '>';

		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $content,
			"html" => '<td width="40%">'.($required? '<span class="adm-required-field">'.$this->GetCustomLabelHTML($id, $content).'</span>': $this->GetCustomLabelHTML($id, $content)).'</td><td>'.$html.'</td>',
			"hidden" => '<input type="hidden" name="'.$id.'" value="'.$value.'">',
		);
	}

	function AddTextField($id, $label, $value, $arParams=array(), $required=false)
	{
		$value = htmlspecialcharsbx(htmlspecialcharsback($value));

		$html = '<textarea name="'.$id.'"';
		if(intval($arParams["cols"]) > 0)
			$html .= ' cols="'.intval($arParams["cols"]).'"';
		if(intval($arParams["rows"]) > 0)
			$html .= ' rows="'.intval($arParams["rows"]).'"';
		$html .= '>'.$value.'</textarea>';

		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $label,
			"html" => '<td width="40%">'.($required? '<span class="adm-required-field">'.$this->GetCustomLabelHTML($id, $label).'</span>': $this->GetCustomLabelHTML($id, $label)).'</td><td>'.$html.'</td>',
			"hidden" => '<input type="hidden" name="'.$id.'" value="'.$value.'">',
			"valign" => "top",
		);
	}

	function AddCalendarField($id, $label, $value, $required=false)
	{
		$html = CalendarDate($id, $value, $this->GetFormName());

		$value = htmlspecialcharsbx(htmlspecialcharsback($value));

		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $label,
			"html" => '<td width="40%">'.($required? '<span class="adm-required-field">'.$this->GetCustomLabelHTML($id, $label).'</span>': $this->GetCustomLabelHTML($id, $label)).'</td><td>'.$html.'</td>',
			"hidden" => '<input type="hidden" name="'.$id.'" value="'.$value.'">',
		);
	}

	function AddCheckBoxField($id, $content, $required, $value, $checked, $arParams=array())
	{
		if (is_array($value))
		{
			$html = '<input type="hidden" name="'.$id.'" value="'.htmlspecialcharsbx($value[1]).'">
				<input type="checkbox" name="'.$id.'" value="'.htmlspecialcharsbx($value[0]).'"'.($checked? ' checked': '');
			$hidden = '<input type="hidden" name="'.$id.'" value="'.htmlspecialcharsbx($checked? $value[0]: $value[1]).'">';
		}
		else
		{
			$html = '<input type="checkbox" name="'.$id.'" value="'.htmlspecialcharsbx($value).'"'.($checked? ' checked': '');
			$hidden = '<input type="hidden" name="'.$id.'" value="'.htmlspecialcharsbx($value).'">';
		}

		foreach($arParams as $param)
			$html .= ' '.$param;
		$html .= '>';

		$label = $this->GetCustomLabelHTML($id, $content);
		if ($required)
		{
			$label = '<span class="adm-required-field">'.$label.'</span>';
		}

		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $content,
			"html" => '<td width="40%">'.$label.'</td><td>'.$html.'</td>',
			"hidden" => $hidden,
		);
	}

	function AddFileField($id, $label, $value, $arParams=array(), $required=false)
	{
		$arDefParams = array("iMaxW"=>150, "iMaxH"=>150, "sParams"=>"border=0", "strImageUrl"=>"", "bPopup"=>true, "sPopupTitle"=>false);
		foreach($arDefParams as $key=>$val)
			if(!array_key_exists($key, $arParams))
				$arParams[$key] = $val;

		$html = CFile::InputFile($id, 20, $value);
		if($value <> '')
			$html .= '<div class="adm-detail-file-image">'.CFile::ShowImage($value, $arParams["iMaxW"], $arParams["iMaxH"], $arParams["sParams"], $arParams["strImageUrl"], $arParams["bPopup"], $arParams["sPopupTitle"])."</div>";

		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $label,
			"html" => '<td width="40%">'.($required? '<span class="adm-required-field">'.$this->GetCustomLabelHTML($id, $label).'</span>': $this->GetCustomLabelHTML($id, $label)).'</td><td>'.$html.'</td>',
			"valign" => "top",
			"rowClass" => "adm-detail-file-row"
		);
	}

	function BeginCustomField($id, $content, $required = false)
	{
		$this->sCurrentLabel = $this->GetCustomLabel($id, $content);
		$this->bCurrentReq = $required;
		$this->tabs[$this->tabIndex]["FIELDS"][$id] = array(
			"id" => $id,
			"required" => $required,
			"content" => $content,
		);

		ob_start();
	}

	function EndCustomField($id, $hidden = "")
	{
		$html = ob_get_contents();
		ob_end_clean();

		$this->tabs[$this->tabIndex]["FIELDS"][$id]["custom_html"] = $html;
		$this->tabs[$this->tabIndex]["FIELDS"][$id]["hidden"] = $hidden;
	}

	function ShowUserFields($PROPERTY_ID, $ID, $bVarsFromForm)
	{
		/**
		 * @global CMain $APPLICATION
		 * @global CUserTypeManager $USER_FIELD_MANAGER
		 */
		global $USER_FIELD_MANAGER, $APPLICATION;

		if($USER_FIELD_MANAGER->GetRights($PROPERTY_ID) >= "W")
		{
			$this->BeginCustomField("USER_FIELDS_ADD", GetMessage("admin_lib_add_user_field"));
			?>
				<tr>
					<td colspan="2" align="left">
						<a href="/bitrix/admin/userfield_edit.php?lang=<?echo LANGUAGE_ID?>&amp;ENTITY_ID=<?echo urlencode($PROPERTY_ID)?>&amp;back_url=<?echo urlencode($APPLICATION->GetCurPageParam($this->name.'_active_tab=user_fields_tab', array($this->name.'_active_tab')))?>"><?echo $this->GetCustomLabelHTML()?></a>
					</td>
				</tr>
			<?
			$this->EndCustomField("USER_FIELDS_ADD", '');
		}

		$arUserFields = $USER_FIELD_MANAGER->GetUserFields($PROPERTY_ID, $ID, LANGUAGE_ID);
		foreach($arUserFields as $FIELD_NAME => $arUserField)
		{
			$arUserField["VALUE_ID"] = intval($ID);
			if(array_key_exists($FIELD_NAME, $this->arCustomLabels))
				$strLabel = $this->arCustomLabels[$FIELD_NAME];
			else
				$strLabel = $arUserField["EDIT_FORM_LABEL"]? $arUserField["EDIT_FORM_LABEL"]: $arUserField["FIELD_NAME"];
			$arUserField["EDIT_FORM_LABEL"] = $strLabel;

			$this->BeginCustomField($FIELD_NAME, $strLabel, $arUserField["MANDATORY"]=="Y");

			if(isset($_REQUEST['def_'.$FIELD_NAME]))
				$arUserField['SETTINGS']['DEFAULT_VALUE'] = $_REQUEST['def_'.$FIELD_NAME];

			echo $USER_FIELD_MANAGER->GetEditFormHTML($bVarsFromForm, $GLOBALS[$FIELD_NAME], $arUserField);

			$form_value = $GLOBALS[$FIELD_NAME];
			if(!$bVarsFromForm)
				$form_value = $arUserField["VALUE"];
			elseif($arUserField["USER_TYPE"]["BASE_TYPE"]=="file")
				$form_value = $GLOBALS[$arUserField["FIELD_NAME"]."_old_id"];

			$hidden = "";
			if(is_array($form_value))
			{
				foreach($form_value as $value)
					$hidden .= '<input type="hidden" name="'.$FIELD_NAME.'[]" value="'.htmlspecialcharsbx($value).'">';
			}
			else
			{
				$hidden .= '<input type="hidden" name="'.$FIELD_NAME.'" value="'.htmlspecialcharsbx($form_value).'">';
			}
			$this->EndCustomField($FIELD_NAME, $hidden);
		}
	}

	function ShowUserFieldsWithReadyData($PROPERTY_ID, $readyData, $bVarsFromForm, $primaryIdName = 'VALUE_ID')
	{
		/**
		 * @global CMain $APPLICATION
		 * @global CUserTypeManager $USER_FIELD_MANAGER
		 */
		global $USER_FIELD_MANAGER, $APPLICATION;

		if($USER_FIELD_MANAGER->GetRights($PROPERTY_ID) >= "W")
		{
			$this->BeginCustomField("USER_FIELDS_ADD", GetMessage("admin_lib_add_user_field"));
			?>
			<tr>
				<td colspan="2" align="left">
					<a href="/bitrix/admin/userfield_edit.php?lang=<?echo LANGUAGE_ID?>&amp;ENTITY_ID=<?echo urlencode($PROPERTY_ID)?>&amp;back_url=<?echo urlencode($APPLICATION->GetCurPageParam($this->name.'_active_tab=user_fields_tab', array($this->name.'_active_tab')))?>"><?echo $this->GetCustomLabelHTML()?></a>
				</td>
			</tr>
			<?
			$this->EndCustomField("USER_FIELDS_ADD", '');
		}

		$arUserFields = $USER_FIELD_MANAGER->getUserFieldsWithReadyData($PROPERTY_ID, $readyData, LANGUAGE_ID, false, $primaryIdName);

		foreach($arUserFields as $FIELD_NAME => $arUserField)
		{
			$arUserField["VALUE_ID"] = intval($readyData[$primaryIdName]);
			if(array_key_exists($FIELD_NAME, $this->arCustomLabels))
				$strLabel = $this->arCustomLabels[$FIELD_NAME];
			else
				$strLabel = $arUserField["EDIT_FORM_LABEL"]? $arUserField["EDIT_FORM_LABEL"]: $arUserField["FIELD_NAME"];
			$arUserField["EDIT_FORM_LABEL"] = $strLabel;

			$this->BeginCustomField($FIELD_NAME, $strLabel, $arUserField["MANDATORY"]=="Y");

			if(isset($_REQUEST['def_'.$FIELD_NAME]))
				$arUserField['SETTINGS']['DEFAULT_VALUE'] = $_REQUEST['def_'.$FIELD_NAME];

			echo $USER_FIELD_MANAGER->GetEditFormHTML($bVarsFromForm, $GLOBALS[$FIELD_NAME], $arUserField);

			$form_value = $GLOBALS[$FIELD_NAME];
			if(!$bVarsFromForm)
				$form_value = $arUserField["VALUE"];
			elseif($arUserField["USER_TYPE"]["BASE_TYPE"]=="file")
				$form_value = $GLOBALS[$arUserField["FIELD_NAME"]."_old_id"];

			$hidden = "";
			if(is_array($form_value))
			{
				foreach($form_value as $value)
					$hidden .= '<input type="hidden" name="'.$FIELD_NAME.'[]" value="'.htmlspecialcharsbx($value).'">';
			}
			else
			{
				$hidden .= '<input type="hidden" name="'.$FIELD_NAME.'" value="'.htmlspecialcharsbx($form_value).'">';
			}
			$this->EndCustomField($FIELD_NAME, $hidden);
		}
	}

	function Buttons($aParams=false, $additional_html="")
	{
		if($aParams === false)
			$this->arButtonsParams = false;
		else
			$this->arButtonsParams = $aParams;
		$this->sButtonsContent = $additional_html;

		while($this->tabIndex < count($this->tabs))
			$this->BeginNextFormTab();
	}

	/**
	 * @param bool|array $arJSButtons
	 * @return void
	 */
	function ButtonsPublic($arJSButtons = false)
	{
		if ($this->bPublicMode)
		{
			if (strlen($_REQUEST['from_module']))
				$this->sButtonsContent .= '<input type="hidden" name="from_module" value="'.htmlspecialcharsbx($_REQUEST['from_module']).'" />';

			ob_start();
			if ($arJSButtons === false)
			{
				echo '
<input type="hidden" name="bxpublic" value="Y" /><input type="hidden" name="save" value="Y" />
<script type="text/javascript">'.$this->publicObject.'.SetButtons(['.$this->publicObject.'.btnSave, '.$this->publicObject.'.btnCancel]);</script>
';
			}
			elseif (is_array($arJSButtons))
			{
				$arJSButtons = array_values($arJSButtons);
				echo '
<input type="hidden" name="bxpublic" value="Y" />
<script type="text/javascript">'.$this->publicObject.'.SetButtons([
';
				foreach ($arJSButtons as $key => $btn)
				{
					if (substr($btn, 0, 1) == '.')
						$btn = $this->publicObject.$btn;
					echo $key ? ',' : '', $btn, "\r\n"; // NO JSESCAPE HERE! string must contain valid js object
				}
				echo '
]);</script>
';
			}
			$this->sButtonsContent .= ob_get_clean();
		}
	}
}

class CAdminFormSettings
{
	public static function getTabsArray($formId)
	{
		$arCustomTabs = array();
		$customTabs = CUserOptions::GetOption("form", $formId);
		if($customTabs && $customTabs["tabs"])
		{
			$arTabs = explode("--;--", $customTabs["tabs"]);
			foreach($arTabs as $customFields)
			{
				if ($customFields == "")
					continue;

				$arCustomFields = explode("--,--", $customFields);
				$arCustomTabID = "";
				foreach($arCustomFields as $customField)
				{
					if($arCustomTabID == "")
					{
						list($arCustomTabID, $arCustomTabName) = explode("--#--", $customField);
						$arCustomTabs[$arCustomTabID] = array(
							"TAB" => $arCustomTabName,
							"FIELDS" => array(),
						);
					}
					else
					{
						list($arCustomFieldID, $arCustomFieldName) = explode("--#--", $customField);
						$arCustomFieldName = ltrim($arCustomFieldName, defined("BX_UTF")? "* -\xa0\xc2": "* -\xa0");
						$arCustomTabs[$arCustomTabID]["FIELDS"][$arCustomFieldID] = $arCustomFieldName;
					}
				}
			}
		}
		return $arCustomTabs;
	}

	public static function setTabsArray($formId, $arCustomTabs, $common = false, $userID = false)
	{
		$option = "";
		if (is_array($arCustomTabs))
		{
			foreach($arCustomTabs as $arCustomTabID => $arTab)
			{
				if (is_array($arTab) && isset($arTab["TAB"]))
				{
					$option .= $arCustomTabID.'--#--'.$arTab["TAB"];
					if (isset($arTab["FIELDS"]) && is_array($arTab["FIELDS"]))
					{
						foreach ($arTab["FIELDS"] as $arCustomFieldID => $arCustomFieldName)
						{
							$option .= '--,--'.$arCustomFieldID.'--#--'.$arCustomFieldName;
						}
					}
				}
				$option .= '--;--';
			}
		}
		CUserOptions::SetOption("form", $formId, array("tabs" => $option), $common, $userID);
	}
}
admin_styles.css000064400000015417147732346240007775 0ustar00/* Main :: admin css */
body {margin:0; padding:0;}
a:hover {color:red;}
.navchain {font-family:Arial; font-size:12px; color:#1F5887;}
hr.tinygrey {color: #DEDEDE; height: 1px}

.leftmenu, .leftmenuact, .leftmenusep {font-family:Arial; font-size:9pt; font-weight:normal; text-decoration:none;}
.leftmenu {color:#556877;}
.leftmenuact {color:#F8270A;}
.leftmenusep {color:#436287;}
.leftmenusepbg {background-color:#DBE9F3}
.leftmenusepdelim {background-color:#B9D3E6}
.leftmenubg {background-color:#F3F3F3}
.hiddenmenu {font-family:Tahoma, Arial,sans-serif; color:#556877; font-size:12px; padding-top:8px; cursor:pointer; line-height:11px;}
.floatmenu {border: solid 1px #82B0D2; background-color:#F3F3F3; padding:5px; line-height: 18px;}
a.leftmenu:hover {text-decoration:underline; color:#556877;}
a.leftmenuact:hover {text-decoration:underline; color:#F8270A;}
a.leftmenusep:hover {color:#436287;}

.tablehead, .tablehead1, .tablehead2, .tablehead3, .tablehead4, .tablehead5, .tableheadbottom, .tableheadtop {background-color:#C2DBED; padding:3px;}
.tablehead1, .tablehead2, .tablehead3 {border-top: 1px solid #A8C2D7; border-bottom: 1px solid #A8C2D7;}
.tablehead1, .tableheadleft {border-left: 1px solid #A8C2D7;}
.tablehead3, .tableheadright {border-right: 1px solid #A8C2D7;}
.tablehead4, .tablehead5 {border-bottom: 1px solid #A8C2D7; border-left: 1px solid #A8C2D7; border-right: 1px solid #A8C2D7}
.tablehead5, .tableheadtop {border-top: 1px solid #A8C2D7;}
.tableheadbottom {border-bottom: 1px solid #A8C2D7}

.tablebody, .tablebody1, .tablebody2, .tablebody3, .tablebody4, .tablebody5, .tablebodyleft, .tablebodyright, .tablebodytop, .tablebodybottom {background-color:#F1F1F1; padding:3px;}
.tablebody1 {border-left:#CED6DB solid 1px; border-bottom:#CED6DB solid 1px; }
.tablebody2, .tablebodybottom {border-bottom:#CED6DB solid 1px;}
.tablebody3 {border-right:#CED6DB solid 1px; border-bottom:#CED6DB solid 1px;}
.tablebody4, .tablebody5 {border-right:#CED6DB solid 1px; border-left:#CED6DB solid 1px; border-bottom:#CED6DB solid 1px;}
.tablebody5, .tablebodytop {border-top:#CED6DB solid 1px; }
.tablebodyleft {border-left:#CED6DB solid 1px;}
.tablebodyright {border-right:#CED6DB solid 1px;}

.selectedbody {background-color:#E0EBF1;}
.tablenullbody {background-color:#FFFFFF;}

.edittable {border:#A9C9E0 1px solid;}
.edittable td {background-color:#F1F1F1; padding:4px;}
.edittable .tablehead {background-color:#E4EDF3; padding:4px;}
.edittable .selectedbody {background-color:#E9E9E9;}
.edittable .tableheadtext {color:#365069;}
.smallpadding td{padding:1px;}
.nopadding td{padding:0px;}

.tableborder {background-color:#8BB6D6;}
.border {border:#A9C9E0 1px solid;}

.filter {border: 1px solid #C2DBED; border-top:none;}
.tablefilterhead {background-color:#C2DBED; padding:3px;}
table.filter .tablebody {background-color:#F3F3F3; padding:3px;}

.tablebodytext, .tableheadtext, .tablefieldtext, .tabletitletext {font-family:Arial; font-size:12px;}
.tableheadtext, .tablebodytext, .tabletitletext {color:#000000}
.tablefieldtext {color:#365069;}

.actions {line-height:14px;}
.notesmall, .note, .attention, .attentionsmall {font-family:Arial; font-weight:normal;}
.notesmall {font-size:11px; color:#000000;}
.note {font-size:12px; color:#000000;}
.attention {font-size:12px; color:red;}
.attentionsmall {font-size:11px; color:red;}

.tablehead .notesmall, .tablehead1 .notesmall, .tablehead2 .notesmall, .tablehead3 .notesmall, .tablehead4 .notesmall, .tableheadbottom .notesmall, .tableheadtop .notesmall, .tableheadleft .notesmall, .tableheadright .notesmall, .selectedbody .notesmall, {color:green;}
.tablebody .note, .tablebody1 .note, .tablebody2 .note, .tablebody3 .note, .tablebody4  .note{color:green;}

a.txttohtmllink {text-decoration:none;}
a.txttohtmllink:hover {text-decoration:underline; color:red;}
a.tablebodylink {font-family:Arial; font-size:12px; text-decoration:none; color:#0167CD;}
.tablehead a.tablebodylink {color:#295576}
a.tablebodylink:hover {text-decoration:underline; color:red;}

.text, .smalltext, .smalltextlink {font-family:Arial; font-weight:normal;}
.text {font-size:12px; color:#000000;}
.smalltext {font-size:11px; color:#000000;}
.smalltextlink {font-size:11px; text-decoration:none}
a.smalltextlink:hover {text-decoration:underline;}
a.smalltext:hover {color:#000000;}

.notetable {background-color:#FFFFEC;}
.legendtext {font-family:Arial; font-size:11px; color:#000000; font-weight:normal;}
.star, .starrequired {font-family:Verdana; font-size:8pt;}
.starrequired {color: #FF0000}

.submenutable {background-color:#FFFFEC;}
.submenutext {font-family:Arial; font-size:9pt; font-weight:normal; color:#4D5F6C; text-decoration:none;}
a.submenutext:hover {text-decoration:underline; color:#4D5F6C;}

.justify {text-align:justify;}
.linktext {font-family:Verdana; font-size:10pt; color:#000000; font-weight:normal;}
.textmain {font-family:Verdana; font-size:12px; line-height: 15px; text-decoration:none;}
.textb {font-family:Arial; font-size:10pt; color:#000000; font-weight:bold;}
.subtitletext {font-family:Arial; color:#000000; font-size:11pt; font-weight:bold;}

.smalltxt, .smalltxtw, .smalltxtws {font-family:Verdana; text-decoration:none}
.smalltxt {font-size:11px; line-height: 13px;}
.smalltxtw {font-size:10px; line-height: 12px; color:#696C72;}
.smalltxtws {font-size:10px; line-height: 12px; color:#FF7979;}
a.smalltxtw:hover {text-decoration:underline;}
a.smalltxtws:hover {text-decoration:underline;}
.tableheads {background-color:#E4E6DB;}
.tableborders {background-color:#9C9A9C;}

.errortext, .oktext, .notetext {font-family:Arial; font-size:10pt; font-weight:bold;}
.errortext {color:red;}
.oktext {color:#005000;}
.notetext {color:green;}

.required {color:red;}
.pointed {color:green;}
.pointed2 {color:blue;}

/* form fields */
form {margin-top: 16px; margin-bottom: 16px;}
.filter form {margin: 0px;}
INPUT.typeinput, INPUT.typefile, TEXTAREA.typearea, SELECT.typeselect {background-color:#FFFFFF; font-size:12px; font-family:Arial;}
INPUT.button {
	padding:2px;
	font-family:Tahoma; font-size:12px;
	color:#FFFFFF; background-color:#6AA2CA;
	border: 2px solid #4083B5;
	cursor: pointer;
}
.tablebodybutton {font-size:12px; font-family: Arial;}
.textareawidth{width:90%}

/*toolbar selectboxes*/
.titlemenu {font-family:Arial, sans-serif; font-size:12px;}
.titlemenuselected {color:#9B1704;}

/*main heading*/
.pagetitle {background-color:#FFFFFF; border-bottom: 1px solid #BECEEE; padding:3px; padding-left:0px; padding-right:0px;}
.titletext {font-family:Arial; color:#000000; font-weight:bold; font-size:17px;}

/*subheading*/
.pagesubtitle {background-color:#EBEBEB; padding:3px; margin-top: 32px; margin-bottom: 16px;}
.h2 {font-family:Tahoma; font-size:13px; font-weight: bold; color:#000000;}

.pagebottom {background-color:#EEEEEE; border-top: 1px solid #DBDBDB; padding:5px;}
.pagebottomtext {font-family:Tahoma; font-size:11px; color:black;}
top_panel.php000066400000037016147732346240007263 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

if($_GET["back_url_pub"] <> "" && !is_array($_GET["back_url_pub"]) && strpos($_GET["back_url_pub"], "/") === 0)
	$_SESSION["BACK_URL_PUB"] = $_GET["back_url_pub"];

if($_GET["back_url_additional"] <> "" && !is_array($_GET["back_url_additional"]) && strpos($_GET["back_url_additional"], "/") === 0)
	$_SESSION["BACK_URL_ADDITIONAL"] = $_GET["back_url_additional"];

$params = DeleteParam(array("logout", "back_url_pub", "back_url_additional", "sessid"));

$arPanelButtons = array();

function _showTopPanelButtonsSection($arPanelButtons, $hkInstance, $section = null)
{
	global $USER;

	foreach ($arPanelButtons as $item):
		if($item["SEPARATOR"] == true)
			continue;
		if ($section == null && isset($item['SECTION']))
			continue;
		if ($section != null && $item['SECTION'] != $section)
			continue;

		$id = isset($item['ID']) ? $item['ID'] : 'bx_top_panel_button_'.RandString();
		$bHasMenu = (is_array($item["MENU"]) && !empty($item["MENU"]));

		if($USER->IsAuthorized())
			echo $hkInstance->PrintTPButton($item);

		if ($item['LINK']):

?><a id="<?=htmlspecialcharsEx($id)?>" href="<?=htmlspecialcharsEx($item['LINK'])?>" class="<?=$item['ICON']?>"<?=isset($item["TITLE"])?' title="'.htmlspecialcharsEx($item["TITLE"]).'"':''?><?=isset($item["TARGET"])?' target="'.htmlspecialcharsEx($item["TARGET"]).'"':''?> hidefocus="true" onfocus="this.blur();"><?=htmlspecialcharsbx($item["TEXT"])?></a><?

		else:

?><span id="<?=htmlspecialcharsEx($id)?>" class="<?=$item['ICON']?>"<?=isset($item["TITLE"])?'title="'.htmlspecialcharsEx($item["TITLE"]).'"':''?>><?=htmlspecialcharsbx($item["TEXT"])?></span><?

		endif;

		if ($bHasMenu || $item['TOOLTIP'] && $item['TOOLTIP_ID']):
?><script type="text/javascript"><?

			if ($item['TOOLTIP']):
				if ($item['TOOLTIP_ID']):

?>
BX.ready(function() {BX.hint(BX('<?=CUtil::JSEscape($id)?>'), '<?=CUtil::JSEscape($item["TITLE"])?>', '<?=CUtil::JSEscape($item['TOOLTIP'])?>', '<?=CUtil::JSEscape($item['TOOLTIP_ID'])?>')});
<?

				endif;
			endif;
			if ($bHasMenu):

?>
BX.adminPanel.registerButton('<?=CUtil::JSEscape($id)?>', {MENU: <?=CUtil::PhpToJsObject($item['MENU'])?>});
<?

			endif;

?></script><?

		endif;
	endforeach;
}

if($USER->IsAuthorized())
{
	$bCanViewSettings = (is_callable(array($USER,'CanDoOperation')) && ($USER->CanDoOperation('view_other_settings') || $USER->CanDoOperation('edit_other_settings')));
	if($bCanViewSettings)
	{
		//Settings
		$settingsUrl = BX_ROOT."/admin/settings.php?lang=".LANG."&mid=".(defined("ADMIN_MODULE_NAME")? ADMIN_MODULE_NAME:"main").($APPLICATION->GetCurPage() <> BX_ROOT."/admin/settings.php"? "&back_url_settings=".urlencode($_SERVER["REQUEST_URI"]):"");
		$arPanelButtons[] = array(
			"TEXT"=>GetMessage("top_panel_settings"),
			"TITLE"=>GetMessage("button_settings"),
			"LINK"=>$settingsUrl,
			"ICON"=>"adm-header-setting-btn",
			"HK_ID"=>"top_panel_settings",
		);
	}

	//Help
	$module = (defined("ADMIN_MODULE_NAME")? ADMIN_MODULE_NAME: "main");
	$page = (defined("HELP_FILE") && strpos(HELP_FILE, '/') === false? HELP_FILE : basename($APPLICATION->GetCurPage()));

	$aActiveSection = $adminMenu->ActiveSection();
	$section = $aActiveSection["help_section"]."/";
	if (defined("HELP_FILE") && strpos(HELP_FILE, $section) === 0)
		$section = "";
}


/*
 * @global \CAdminPage $adminPage
 */

$arLangs = CLanguage::GetLangSwitcherArray();

$arLangButton = array();
$arLangMenu = array();

foreach($arLangs as $adminLang)
{
	if ($adminLang['SELECTED'])
	{
		$arLangButton = array(
			"TEXT"=>ToUpper($adminLang["LID"]),
			"TITLE"=>GetMessage("top_panel_lang")." ".$adminLang["NAME"],
			"LINK"=>htmlspecialcharsback($adminLang["PATH"]),
			"SECTION" => 1,
			"ICON" => "adm-header-language",
		);
	}

	$arLangMenu[] = array(
		"TEXT" => '('.$adminLang["LID"].') '.$adminLang["NAME"],
		"TITLE"=> GetMessage("top_panel_lang")." ".$adminLang["NAME"],
		"LINK"=>htmlspecialcharsback($adminLang["PATH"]),
	);
}

if (count($arLangMenu) > 1)
{
	CJSCore::Init(array('admin_interface'));
	$arLangButton['MENU'] = $arLangMenu;
}

$arPanelButtons[] = $arLangButton;

$sPubUrl = ($_SESSION["BACK_URL_PUB"] <> ""?
	htmlspecialcharsbx($_SESSION["BACK_URL_PUB"]).(strpos($_SESSION["BACK_URL_PUB"], "?") !== false? "&amp;":"?") : '/?').
	'back_url_admin='.urlencode($APPLICATION->GetCurPage().($params<>""? "?".$params:""));

if (\Bitrix\Main\Config\Option::get("sale", "~IS_SALE_CRM_SITE_MASTER_FINISH") === "Y")
{
	$defaultSite = \Bitrix\Main\SiteTable::getList([
		"select" => ["SERVER_NAME"],
		"filter" => ["=DEF" => "Y"]
	])->fetch();
	if ($defaultSite && isset($defaultSite["SERVER_NAME"]) && !empty($defaultSite["SERVER_NAME"]))
	{
		$sPubUrl = ((\Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https" : "http")."://".$defaultSite["SERVER_NAME"]).$sPubUrl;
	}
	elseif ($serverName = \Bitrix\Main\Config\Option::get("main", "server_name"))
	{
		$sPubUrl = ((\Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https" : "http")."://".$serverName).$sPubUrl;
	}
}
elseif (\Bitrix\Main\Config\Option::get("sale", "~IS_SALE_BSM_SITE_MASTER_FINISH") === "Y"
	&& $additionalSiteId = \Bitrix\Main\Config\Option::get("sale", "~BSM_WIZARD_SITE_ID")
)
{
	$additionalSite = \Bitrix\Main\SiteTable::getList([
		"select" => ["SERVER_NAME"],
		"filter" => ["LID" => $additionalSiteId]
	])->fetch();
	if ($additionalSite && !empty($additionalSite["SERVER_NAME"]))
	{
		$sPubUrl = ((\Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https" : "http")."://".$additionalSite["SERVER_NAME"]).$sPubUrl;
	}
}

$aUserOptGlobal = CUserOptions::GetOption("global", "settings");

if($USER->IsAuthorized())
{
	$hkInstance = CHotKeys::getInstance();
	$Execs=$hkInstance->GetCodeByClassName("top_panel_menu",GetMessage("admin_panel_menu"));
	echo $hkInstance->PrintJSExecs($Execs);
	$Execs=$hkInstance->GetCodeByClassName("admin_panel_site",GetMessage("admin_panel_site"));
	echo $hkInstance->PrintJSExecs($Execs);
	$Execs=$hkInstance->GetCodeByClassName("admin_panel_admin",GetMessage("admin_panel_admin"));
	echo $hkInstance->PrintJSExecs($Execs);
}
?>
<div id="bx-panel" class="adm-header"><div class="adm-header-left">
	<div class="adm-header-btn-wrap">
		<a hidefocus="true" href="<?=$sPubUrl?>" id="bx-panel-view-tab" class="adm-header-btn adm-header-btn-site" title="<?=GetMessage("adm_top_panel_view_title")?>"><?=GetMessage("admin_panel_site")?></a>
		<?php
		$isDefault = true;

		if (\Bitrix\Main\Config\Option::get("sale", "~IS_SALE_CRM_SITE_MASTER_FINISH") === "Y"
			&& $additionalSiteId = \Bitrix\Main\Config\Option::get("sale", "~CRM_WIZARD_SITE_ID")
		)
		{
			$additionalTabTitle = GetMessage("adm_top_panel_view_b24_title");
			$additionalTabMessage = GetMessage("admin_panel_b24");

			$additionalSite = \Bitrix\Main\SiteTable::getList([
				"select" => ["SERVER_NAME"],
				"filter" => ["LID" => $additionalSiteId]
			])->fetch();
			if ($additionalSite && !empty($additionalSite["SERVER_NAME"]))
			{
				$isDefault = false;

				$additionalSiteUrl = ($_SESSION["BACK_URL_ADDITIONAL"] <> ""
					? htmlspecialcharsbx($_SESSION["BACK_URL_ADDITIONAL"]).(strpos($_SESSION["BACK_URL_ADDITIONAL"], "?") !== false? "&amp;":"?")
					: '/?').'back_url_admin='.urlencode($APPLICATION->GetCurPage().($params<>"" ? "?".$params : ""));

				$additionalSiteHost = \Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https://" : "http://";
				$additionalSiteServerName = $additionalSiteHost.$additionalSite["SERVER_NAME"].$additionalSiteUrl;
				?>
				<a hidefocus="true" href="<?=BX_ROOT."/admin/index.php?lang=".LANGUAGE_ID?>" class="adm-header-btn adm-header-btn-admin"><?=GetMessage("admin_panel_admin")?></a>
				<a hidefocus="true" href="<?=$additionalSiteServerName?>" id="bx-panel-view-tab" class="adm-header-btn adm-header-btn-crm" title="<?=$additionalTabTitle?>"><?=$additionalTabMessage?></a>
				<?php
			}
		}
		elseif (\Bitrix\Main\Config\Option::get("sale", "~IS_SALE_BSM_SITE_MASTER_FINISH") === "Y"
			&& $additionalSiteId = \Bitrix\Main\Config\Option::get("sale", "~BSM_WIZARD_SITE_ID")
		)
		{
			$additionalSite = \Bitrix\Main\SiteTable::getList([
				"select" => ["SERVER_NAME"],
				"filter" => ["LID" => $additionalSiteId]
			])->fetch();
			if ($additionalSite)
			{
				$defaultSite = \Bitrix\Main\SiteTable::getList([
					"select" => ["SERVER_NAME"],
					"filter" => ["=DEF" => "Y"]
				])->fetch();

				if ($defaultSite && isset($defaultSite["SERVER_NAME"]) && !empty($defaultSite["SERVER_NAME"]))
				{
					$defaultServerName = (\Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https" : "http")."://".$defaultSite["SERVER_NAME"];
				}
				elseif ($serverName = \Bitrix\Main\Config\Option::get("main", "server_name"))
				{
					$defaultServerName = (\Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https" : "http")."://".$serverName;
				}

				if ($defaultServerName)
				{
					$isDefault = false;
					$additionalTabTitle = GetMessage("adm_top_panel_view_b24_title");
					$additionalTabMessage = GetMessage("admin_panel_b24");

					$additionalSiteUrl = ($_SESSION["BACK_URL_ADDITIONAL"] <> ""
							? htmlspecialcharsbx($_SESSION["BACK_URL_ADDITIONAL"]).(strpos($_SESSION["BACK_URL_ADDITIONAL"], "?") !== false? "&amp;":"?")
							: '/?').'back_url_admin='.urlencode($APPLICATION->GetCurPage().($params<>"" ? "?".$params : ""));
					$defaultServerName = $defaultServerName.$additionalSiteUrl;
					?>
					<a hidefocus="true" href="<?=BX_ROOT."/admin/index.php?lang=".LANGUAGE_ID?>" class="adm-header-btn adm-header-btn-admin"><?=GetMessage("admin_panel_admin")?></a>
					<a hidefocus="true" href="<?=$defaultServerName?>" id="bx-panel-view-tab" class="adm-header-btn adm-header-btn-crm" title="<?=$additionalTabTitle?>"><?=$additionalTabMessage?></a>
					<?php
				}
			}
		}

		if ($isDefault)
		{
			?>
			<a hidefocus="true" href="<?=BX_ROOT."/admin/index.php?lang=".LANGUAGE_ID?>" class="adm-header-btn adm-header-btn-admin"><?=GetMessage("admin_panel_admin")?></a>
			<?php
		}
		?>
	</div>
<?php
$informerItemsCount = CAdminInformer::InsertMainItems();

if ($USER->IsAuthorized() && $informerItemsCount>0):

?><span class="adm-header-notif-block" id="adm-header-notif-block" onclick="BX.adminInformer.Toggle(this);" title="<?=GetMessage("admin_panel_notif_block_title")?>"><span class="adm-header-notif-icon"></span><span class="adm-header-notif-counter" id="adm-header-notif-counter"><?=CAdminInformer::$alertCounter?></span></span><?
endif;

_showTopPanelButtonsSection($arPanelButtons, $hkInstance)

?></div><div class="adm-header-right"><?
if($USER->IsAuthorized() && IsModuleInstalled("search")):

?><div class="adm-header-search-block" id="bx-search-box"><input class="adm-header-search" id="bx-search-input" onfocus="if (this.value=='<?=GetMessage("top_panel_search_def")?>') {this.value=''; BX.addClass(this.parentNode,'adm-header-search-block-active');}" value="<?=GetMessage("top_panel_search_def")?>" onblur="if (this.value==''){this.value='<?=GetMessage("top_panel_search_def")?>'; BX.removeClass(this.parentNode,'adm-header-search-block-active');}" type="text" autocomplete="off" /><a href="#" onclick="BX('bx-search-input').value=''; BX('bx-search-input').onblur();" class="adm-header-search-block-btn"></a></div><script type="text/javascript">
var jsControl = new JCAdminTitleSearch({
	'AJAX_PAGE' : '/bitrix/admin/get_search.php?lang=<?=LANGUAGE_ID?>',
	'CONTAINER_ID': 'bx-search-box',
	'INPUT_ID': 'bx-search-input',
	'MIN_QUERY_LEN': 1
});
</script><?

	$Execs = $hkInstance->GetCodeByClassName("bx-search-input", GetMessage("top_panel_search_def"));
	echo $hkInstance->PrintJSExecs($Execs);

endif;
?><div class="adm-header-right-block"><?

if ($USER->IsAuthorized()):

/*
 * @global \CAdminPage $adminPage
 */

	$ssoSwitcher = $adminPage->getSSOSwitcherButton();
	$bShowSSO = is_array($ssoSwitcher) && count($ssoSwitcher) > 0;

	$userName = $USER->GetFormattedName();
	if($bShowSSO)
	{
		$userName = '<span class="adm-header-separate-left">'.$userName.'</span><span class="adm-header-separate-right" id="bx-panel-sso"></span>';
	}

	if ($USER->CanDoOperation('view_own_profile') || $USER->CanDoOperation('edit_own_profile')):

?><a hidefocus="true" href="/bitrix/admin/user_edit.php?lang=<?=LANGUAGE_ID?>&amp;ID=<?=$USER->GetID()?>" class="adm-header-user-block<?=$bShowSSO ? ' adm-header-separate' : ''?>" onfocus="this.blur()"><?=$userName;?></a><?

	else:

?><span class="adm-header-user-block<?=$bShowSSO ? ' adm-header-separate' : ''?>" id="bx-panel-user"><?=$userName?></span><?

	endif;

	if($bShowSSO)
	{
?>
<script>BX.adminPanel.registerButton('bx-panel-sso', {MENU: <?=CUtil::PhpToJsObject($ssoSwitcher)?>});</script>
<?
	}

?><a hidefocus="true" href="<?=htmlspecialcharsbx((defined('BX_ADMIN_SECTION_404') && BX_ADMIN_SECTION_404 == 'Y' ? '/bitrix/admin/' : $APPLICATION->GetCurPage())).'?logout=yes'.htmlspecialcharsbx(($s=DeleteParam(array("logout"))) == ""? "":"&".$s)?>" class="adm-header-exit" id="bx-panel-logout" title="<?=GetMessage('admin_panel_logout_title')?>"><?=GetMessage("admin_panel_logout")?></a><?

	$Execs = $hkInstance->GetCodeByClassName("bx-panel-logout",GetMessage('admin_panel_logout'));
	echo $hkInstance->PrintJSExecs($Execs);

endif;


_showTopPanelButtonsSection($arPanelButtons, $hkInstance, 1);

if ($USER->IsAuthorized()):
	if($hkInstance->IsActive()):

?><a hidefocus="true" id="bx-panel-hotkeys" href="javascript:void(0)" onclick="BXHotKeys.ShowSettings();" class="header-keyboard" title="<?=GetMessage('admin_panel_hotkeys_title')?>"></a><?

	endif;

	$aUserOpt = CUserOptions::GetOption("admin_panel", "settings");

?><a hidefocus="true" href="javascript:void(0)" id="bx-panel-pin" class="adm-header-pin" onclick="BX.adminPanel.Fix(this)" title="<?=GetMessage('top_panel_pin_'.($aUserOpt['fix'] == 'on' ? 'off' : 'on'))?>"></a><?

	if(LANGUAGE_ID == "ru")
	{
		CJSCore::Init(array('helper'));
		$helpUrl = CHTTP::urlAddParams('https://helpdesk.bitrix24.ru/widget2/dev/', array(
				"url" => urlencode("https://".$_SERVER["HTTP_HOST"].$APPLICATION->GetCurPageParam()),
				"user_id" => $USER->GetID(),
				"is_admin" => $USER->IsAdmin() ? 1 : 0,
				"help_url" => urlencode("http://dev.1c-bitrix.ru/user_help/".$section.(defined("HELP_FILE") && strpos(HELP_FILE, '/') !== false?  HELP_FILE : $module."/".$page))
			)
		);
		$frameOpenUrl = CHTTP::urlAddParams($helpUrl, array(
				"action" => "open",
			)
		);
		$frameCloseUrl = CHTTP::urlAddParams($helpUrl, array(
				"action" => "close",
			)
		);
		?>
		<span class="adm-header-help-btn" id="bx_top_panel_button_helper" <?if (!isset($helperHeroOption["show"])):?>onclick="BX.userOptions.save('main', 'helper_hero_admin',  'show', 'Y');"<?endif?>>
		   <span class="adm-header-help-btn-icon"></span>
		   <span class="adm-header-help-btn-text"><?=GetMessage("top_panel_help")?></span>
		</span>
		<script>
			BX.Helper.init({
				frameOpenUrl : '<?=$frameOpenUrl?>',
				helpBtn : BX('bx_top_panel_button_helper'),
				langId: '<?=LANGUAGE_ID?>',
				needCheckNotify: 'N',
				isAdmin: 'Y'
			});
		</script>
		<?
	}
	else
	{
		$helpLink = "http://www.bitrixsoft.com/help/index.html?page=" . urlencode("source/" . $module . "/help/en/" . $page . ".html");
		?>
		<span onclick="document.location.href = '<?=$helpLink?>';" class="adm-header-help-btn" id="bx_top_panel_button_helper">
		   <span class="adm-header-help-btn-icon"></span>
		   <span class="adm-header-help-btn-text"><?=GetMessage("top_panel_help")?></span>
		</span>
		<?
	}
?>

<?
	$Execs = $hkInstance->GetCodeByClassName("bx-panel-pin",GetMessage('top_panel_pin'));
	echo $hkInstance->PrintJSExecs($Execs);

endif;
?></div></div><div class="adm-header-bottom"></div><?

if ($USER->IsAdmin())
	echo CAdminNotify::GetHtml();

?></div><?

echo $GLOBALS["adminPage"]->ShowSound();
?>
debug_info.php000066400000103714147732346240007402 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

// ************************************************************************
// $main_exec_time, $bShowTime, $bShowStat MUST be defined before include
// ************************************************************************

global $APPLICATION;
$application = \Bitrix\Main\Application::getInstance();
$sqlTracker  = $application->getConnection()->getTracker();

echo CJSCore::Init('admin_interface', true);
?>
<style>
div.bx-debug-content-table tr.heading td {background-color:#E1EEDA;}
div.bx-debug-content-table tr.heading-sort td {white-space:nowrap; border-bottom:solid 1px #dce7ed; cursor:pointer;}
div.bx-debug-content-table tr.cache-row {vertical-align:top;}
div.bx-debug-content-table tr.cache-row td {white-space:nowrap;}
div.bx-debug-content-table tr.heading-bottom td {padding:3px 3px 9px 3px !important;}
div.bx-debug-content-table td {padding-right:4px !important; padding-bottom:4px !important;}
div.bx-debug-content-table td.number {padding-right:4px !important; padding-bottom:4px !important; text-align:right !important; white-space:nowrap !important}
div.bx-debug-content-top {padding:12px; position:relative; top:0px; left:0px; height:120px; overflow:auto; border-bottom:1px solid #D0D0D0;}
</style>
<?
if($bShowTime || $bShowStat || $bShowCacheStat)
{
?>
<div class="bx-component-debug bx-debug-summary">
<?
}

$bShowExtTime = $bShowTime && !defined("ADMIN_SECTION") && $bShowStat;
$DOCUMENT_ROOT_LEN = strlen($_SERVER["DOCUMENT_ROOT"]);

if($bShowExtTime)
{
	$START_EXEC_CURRENT_TIME = microtime();

	list($usec, $sec) = explode(" ", START_EXEC_PROLOG_AFTER_2);
	$PROLOG_AFTER_2 = (float)$sec + (float)$usec;
	list($usec, $sec) = explode(" ", START_EXEC_PROLOG_AFTER_1);
	$PROLOG_AFTER_1 = (float)$sec + (float)$usec;
	$PROLOG_AFTER = $PROLOG_AFTER_2 - $PROLOG_AFTER_1;

	list($usec, $sec) = explode(" ", START_EXEC_AGENTS_2);
	$AGENTS_2 = (float)$sec + (float)$usec;
	list($usec, $sec) = explode(" ", START_EXEC_AGENTS_1);
	$AGENTS_1 = (float)$sec + (float)$usec;
	$AGENTS = $AGENTS_2 - $AGENTS_1;

	list($usec, $sec) = explode(" ", START_EXEC_PROLOG_BEFORE_1);
	$PROLOG_BEFORE_1 = (float)$sec + (float)$usec;
	$PROLOG_BEFORE = $PROLOG_AFTER_1 - $PROLOG_BEFORE_1 - $AGENTS;

	$PROLOG = $PROLOG_AFTER_2 - $PROLOG_BEFORE_1;

	list($usec, $sec) = explode(" ", START_EXEC_EPILOG_BEFORE_1);
	$EPILOG_BEFORE_1 = (float)$sec + (float)$usec;

	$WORK_AREA = $EPILOG_BEFORE_1 - $PROLOG_AFTER_2;

	list($usec, $sec) = explode(" ", START_EXEC_EPILOG_AFTER_1);
	$EPILOG_AFTER_1 = (float)$sec + (float)$usec;

	$EPILOG_BEFORE = $EPILOG_AFTER_1 - $EPILOG_BEFORE_1;

	list($usec, $sec) = explode(" ", $START_EXEC_CURRENT_TIME);
	$CURRENT_TIME = (float)$sec + (float)$usec;

	$EPILOG_AFTER = $CURRENT_TIME - $EPILOG_AFTER_1;

	$EPILOG = $CURRENT_TIME - $EPILOG_BEFORE_1;

	$PAGE = $CURRENT_TIME - $PROLOG_BEFORE_1;

	$arAreas = array(
		"PAGE"          => array("FLT" => array("PB", "AG", "PA", "WA", "EB", "EV", "EA"), "TIME" => $PAGE),
		"PROLOG"        => array("FLT" => array("PB", "AG", "PA"                        ), "TIME" => $PROLOG),
		"PROLOG_BEFORE" => array("FLT" => array("PB"                                    ), "TIME" => $PROLOG_BEFORE),
		"AGENTS"        => array("FLT" => array(      "AG"                              ), "TIME" => $AGENTS),
		"PROLOG_AFTER"  => array("FLT" => array(            "PA"                        ), "TIME" => $PROLOG_AFTER),
		"WORK_AREA"     => array("FLT" => array(                  "WA"                  ), "TIME" => $WORK_AREA),
		"EPILOG"        => array("FLT" => array(                        "EB", "EV", "EA"), "TIME" => $EPILOG),
		"EPILOG_BEFORE" => array("FLT" => array(                        "EB"            ), "TIME" => $EPILOG_BEFORE),
		"EPILOG_AFTER"  => array("FLT" => array(                              "EV", "EA"), "TIME" => $EPILOG_AFTER),
	);

	$j = 1;
	foreach($arAreas as $i => $arArea)
	{
		$arAreas[$i]["NUM"] = $j;
		$j++;

		$arAreas[$i]["TRACE"] = array(
			"PATH" => $APPLICATION->GetCurPage(),
			"QUERY_COUNT" => 0,
			"QUERY_TIME" => 0.0,
			"QUERIES" => array(),
			"TIME" => $arArea["TIME"],
			"COMPONENT_COUNT" => 0,
			"COMPONENT_TIME" => 0.0,
			"COMP_QUERY_COUNT" => 0,
			"COMP_QUERY_TIME" => 0.0,
			"CACHE_SIZE" => 0,
		);
	}

	$state = "PB";
	foreach($sqlTracker->getQueries() as $arQueryDebug)
	{
		if (strlen($arQueryDebug["BX_STATE"]) > 0)
			$state = $arQueryDebug["BX_STATE"];

		foreach($arAreas as $i => $arArea)
		{
			if(in_array($state, $arArea["FLT"]))
			{
				$arAreas[$i]["TRACE"]["QUERY_COUNT"]++;
				$arAreas[$i]["TRACE"]["QUERY_TIME"]+=$arQueryDebug["TIME"];
				//$arAreas[$i]["TRACE"]["QUERIES"][] = $arQueryDebug;
			}
		}
	}

	$state = "PA";
	foreach($APPLICATION->arIncludeDebug as $arIncludeDebug)
	{
		if (strlen($arIncludeDebug["BX_STATE"]) > 0)
			$state = $arIncludeDebug["BX_STATE"];

		foreach($arAreas as $i => $arArea)
		{
			if(in_array($state, $arArea["FLT"]))
			{
				$arAreas[$i]["TRACE"]["TIME"] -= $arIncludeDebug["TIME"];
				$arAreas[$i]["TRACE"]["COMPONENT_COUNT"]++;
				$arAreas[$i]["TRACE"]["COMPONENT_TIME"] += $arIncludeDebug["TIME"];
				$arAreas[$i]["TRACE"]["COMP_QUERY_COUNT"] += $arIncludeDebug["QUERY_COUNT"];
				$arAreas[$i]["TRACE"]["COMP_QUERY_TIME"] += $arIncludeDebug["QUERY_TIME"];
				$arAreas[$i]["TRACE"]["CACHE_SIZE"] += $arIncludeDebug["CACHE_SIZE"];
			}
		}
	}

	$bShowComps = count($APPLICATION->arIncludeDebug) > 0;

	foreach($arAreas as $i => $arArea)
	{
		$arAreas[$i]["IND"] = count($APPLICATION->arIncludeDebug);
		$APPLICATION->arIncludeDebug[]=$arArea["TRACE"];
	}

	echo '<a href="javascript:jsDebugTimeWindow.Show(); jsDebugTimeWindow.ShowDetails(\'BX_DEBUG_TIME_1_1\')">'.GetMessage("debug_info_cr_time").'</a> <span id="bx_main_exec_time">'.round($PAGE, 4).'</span> '.GetMessage("debug_info_sec").'<br>';
}
elseif($bShowTime)
{
	echo GetMessage("debug_info_cr_time").' <span id="bx_main_exec_time">'.round($main_exec_time, 4).'</span> '.GetMessage("debug_info_sec").'<br />';
}

$totalQueryCount = 0;
$totalQueryTime = 0.0;

if($bShowStat || $bShowCacheStat)
{
	if ($bShowStat)
	{
		$totalQueryCount = $sqlTracker->getCounter();
		$totalQueryTime = $sqlTracker->getTime();
		foreach($APPLICATION->arIncludeDebug as $i=>$arIncludeDebug)
		{
			if(array_key_exists("REL_PATH", $arIncludeDebug))
			{
				$totalQueryCount += $arIncludeDebug["QUERY_COUNT"];
				$totalQueryTime += $arIncludeDebug["QUERY_TIME"];
			}
		}
		echo '<a title="'.GetMessage("debug_info_query_title").'" href="javascript:BX_DEBUG_INFO_'.count($APPLICATION->arIncludeDebug).'.Show(); BX_DEBUG_INFO_'.count($APPLICATION->arIncludeDebug).'.ShowDetails(\'BX_DEBUG_INFO_'.count($APPLICATION->arIncludeDebug).'_1\');">'.GetMessage("debug_info_total_queries")."</a> ".intval($totalQueryCount)."<br>";
		echo GetMessage("debug_info_total_time")." ".round($totalQueryTime, 4)." ".GetMessage("debug_info_sec")."<br>";
	}

	if($GLOBALS["CACHE_STAT_BYTES"] || $bShowCacheStat)
	{
		$arCacheDebug = \Bitrix\Main\Diag\CacheTracker::getCacheTracking();
		if (!empty($arCacheDebug))
		{
			echo '<a title="'.GetMessage("debug_info_query_title").'" href="javascript:BX_DEBUG_INFO_CACHE.Show(); BX_DEBUG_INFO_CACHE.ShowDetails(\'BX_DEBUG_INFO_CACHE_m_0\');">'.GetMessage("debug_info_cache_size")."</a> "." ",CFile::FormatSize(\Bitrix\Main\Diag\CacheTracker::getCacheStatBytes(), 0)." (".count($arCacheDebug).")<br>";
		}
		else
		{
			echo GetMessage("debug_info_cache_size")." ",CFile::FormatSize(\Bitrix\Main\Diag\CacheTracker::getCacheStatBytes(), 0)."<br>";
		}
	}
}

if($bShowTime || $bShowStat)
{
	echo '</div><div class="empty"></div>';
}

if ($bShowStat || $bShowCacheStat) //2
{
	$APPLICATION->arIncludeDebug[] = array(
		"PATH" => $APPLICATION->GetCurPage(),
		"QUERY_COUNT" => $totalQueryCount,
		"QUERY_TIME" => round($totalQueryTime, 4),
		"QUERIES" => $sqlTracker,
		"TIME" => $main_exec_time,
	);

	//CJSPopup
	require_once($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/interface/admin_lib.php");

	$arCacheDebug = \Bitrix\Main\Diag\CacheTracker::getCacheTracking();
	if (!empty($arCacheDebug))
	{
		?>
		<script type="text/javascript">
			function sortTable(table_id, column_num, reverse)
			{
				var table = BX(table_id);
				var title = table.rows[0].cells[column_num].innerHTML;
				if (title.charCodeAt(0) == 8595)
					reverse = true;
				if (title.charCodeAt(0) == 8593)
					reverse = false;

				for (var i = 1; i < table.rows.length; i++)
				{
					for (var j = 1; j < table.rows.length; j++)
					{
						var a = table.rows[i].cells[column_num].getAttribute('sort')? table.rows[i].cells[column_num].getAttribute('sort'): table.rows[i].cells[column_num].innerHTML;
						var ai = parseInt(a);
						if (ai > 0) a = ai;
						var b = table.rows[j].cells[column_num].getAttribute('sort')? table.rows[j].cells[column_num].getAttribute('sort'): table.rows[j].cells[column_num].innerHTML;
						var bi = parseInt(b);
						if (bi > 0) b = bi;

						if ((!reverse && a < b) || (reverse && a > b))
						{
							table.tBodies[0].insertBefore(table.rows[i], table.rows[j]);
						}
					}
				}

				for (var i = 0; i < table.rows[0].cells.length; i++)
				{

					var title = table.rows[0].cells[i].innerHTML;
					if (
						title.charCodeAt(0) == 8595
						|| title.charCodeAt(0) == 8593
					)
						table.rows[0].cells[i].innerHTML = title.substr(1);

					if (i == column_num)
						table.rows[0].cells[i].innerHTML = (reverse? '&uarr;': '&darr;') + table.rows[0].cells[i].innerHTML;
				}
			}
			BX_DEBUG_INFO_CACHE = new BX.CDebugDialog();
		</script>
		<?
		$obJSPopup = new CJSPopupOnPage('', array());
		$obJSPopup->jsPopup = 'BX_DEBUG_INFO_CACHE';
		$obJSPopup->StartDescription('bx-debug-window');
		?>
		<p><?echo GetMessage("debug_info_cache_size")?> <?=CFile::FormatSize(\Bitrix\Main\Diag\CacheTracker::getCacheStatBytes(), 0)?></p>
		<?
		$obJSPopup->StartContent(array('buffer' => true));
		?>
		<div class="bx-debug-content bx-debug-content-table">
			<table id="cacheDebug" cellpadding="2" cellspacing="0" border="0">
				<tr class="heading-sort">
					<td onclick="sortTable('cacheDebug', 0)">&darr;&nbsp;</td>
					<td onclick="sortTable('cacheDebug', 1)"><?echo GetMessage("debug_info_cache_table_func");?></td>
					<td onclick="sortTable('cacheDebug', 2, true)"><?echo GetMessage("debug_info_cache_table_size");?></td>
					<td onclick="sortTable('cacheDebug', 3)"><?echo GetMessage("debug_info_cache_file_path");?></td>
				</tr>
				<?
				foreach($arCacheDebug as $j => $cacheDebug)
				{
					if (substr($cacheDebug["path"], 0, $DOCUMENT_ROOT_LEN) === $_SERVER["DOCUMENT_ROOT"])
						$path = '<a target="blank" href="/bitrix/admin/fileman_file_view.php?path='.urlencode(substr($cacheDebug["path"], $DOCUMENT_ROOT_LEN)).'&lang='.LANGUAGE_ID.'">'.htmlspecialcharsEx(substr($cacheDebug["path"], $DOCUMENT_ROOT_LEN)).'</a>';
					else
						$path = '&nbsp;';
				?>
				<tr class="cache-row">
					<td class="number"><?echo $j+1?></td>
					<td><a href="javascript:BX_DEBUG_INFO_CACHE.ShowDetails('BX_DEBUG_INFO_CACHE_m_<?=$j?>')"><?echo $cacheDebug["callee_func"]?></a></td>
					<td class="number" sort="<?echo $cacheDebug["cache_size"]?>"><?=CFile::FormatSize($cacheDebug["cache_size"], 0)?></td>
					<td><?=$path?></td>
				</tr>
				<?
				}
				?>
			</table>
		</div>#DIVIDER#<div class="bx-debug-content bx-debug-content-details">
			<?
				foreach($arCacheDebug as $j => $cacheDebug)
				{
					?><div id="BX_DEBUG_INFO_CACHE_m_<?=$j?>" style="display:none">
					<b><?echo GetMessage("debug_info_query_from")?></b>
					<?
					$k=1;
					foreach($cacheDebug["TRACE"] as $n => $tr)
					{
						?>
						<br /><br />
						<b>(<?echo ($n + 1)?>)</b>
						<?
						echo $tr["file"].":".$tr["line"]."<br /><nobr>".htmlspecialcharsbx($tr["func"]);
						if($n == 0)
							echo "(...)</nobr>";
						else
							echo "</nobr>(".htmlspecialcharsbx(print_r($tr["args"], true)).")";
					} //$back_trace
					?></div>
					<?
				}; // $arQueries
				?>
			</div>
			<?
		$obJSPopup->StartButtons();
		$obJSPopup->ShowStandardButtons(array('close'));
	}
?>
		<script type="text/javascript">
			var tableRows;
			function filterTable(input, table_id, column_num)
			{
				var table = BX(table_id);
				for (var i = 0; i < table.rows.length; i++)
				{
					var sql = table.rows[i].cells[column_num].innerHTML;
					if (input.value.length > 0 && sql.indexOf(input.value) == -1)
						table.rows[i].style.display = 'none';
					else
						table.rows[i].style.display = 'block';
				}
			}
			BX_DEBUG_INFO_CACHE = new BX.CDebugDialog();
		</script>
<?
	foreach($APPLICATION->arIncludeDebug as $i=>$arIncludeDebug)
	{
		?>
		<script type="text/javascript">
			BX_DEBUG_INFO_<?=$i?> = new BX.CDebugDialog();
		</script>
		<?
		$obJSPopup = new CJSPopupOnPage('', array());
		$obJSPopup->jsPopup = 'BX_DEBUG_INFO_'.$i;
		$obJSPopup->StartDescription('bx-core-debug-info');
		?>
		<p><?echo GetMessage("debug_info_path")?> <?=$arIncludeDebug["PATH"]?></p>
		<p><?echo GetMessage("debug_info_time")?> <?=$arIncludeDebug["TIME"]?> <?echo GetMessage("debug_info_sec")?></p>
		<p><?echo GetMessage("debug_info_queries")?> <?=$arIncludeDebug["QUERY_COUNT"]?>, <?echo GetMessage("debug_info_time1")?> <?=$arIncludeDebug["QUERY_TIME"]?> <?echo GetMessage("debug_info_sec")?><?if($arIncludeDebug["TIME"] > 0):?> (<?=round($arIncludeDebug["QUERY_TIME"]/$arIncludeDebug["TIME"]*100, 2)?>%)<?endif?></p>
		<p><?echo GetMessage("debug_info_search")?>: <input type="text" style="height:16px" onkeydown="filterTable(this, 'queryDebug<?echo $i?>', 1)" onpaste="filterTable(this, 'queryDebug<?echo $i?>', 1)" oninput="filterTable(this, 'queryDebug<?echo $i?>', 1)"></p>
		<?
		$obJSPopup->StartContent(array('buffer' => true));
		if (!empty($arIncludeDebug["QUERIES"]))
		{
			?><div class="bx-debug-content bx-debug-content-table"><?
				$arQueries = array();
				foreach($arIncludeDebug["QUERIES"] as $j=>$arQueryDebug)
				{
					$strSql = $arQueryDebug["QUERY"];
					$arQueries[$strSql]["COUNT"]++;
					$arQueries[$strSql]["CALLS"][] = array(
						"TIME"=>$arQueryDebug["TIME"],
						"TRACE"=>$arQueryDebug["TRACE"]
					);
				}
				?><table id="queryDebug<?echo $i?>" cellpadding="0" cellspacing="0" border="0"><?
					$j = 1;
					foreach($arQueries as $strSql=>$query)
					{
						?><tr>
							<td class="number" valign="top"><?echo $j?></td>
							<td><a href="javascript:BX_DEBUG_INFO_<?=$i?>.ShowDetails('BX_DEBUG_INFO_<?=$i."_".$j?>')"><?echo htmlspecialcharsbx(substr($strSql, 0, 100))."..."?></a>&nbsp;(<?echo $query["COUNT"]?>) </td>
							<td class="number" valign="top"><?
								$t = 0.0;
								foreach($query["CALLS"] as $call)
									$t += $call["TIME"];
								echo number_format($t/$query["COUNT"], 5);
							?></td>
						</tr><?
						$j++;
					} //$arQueries
				?></table>
			</div>#DIVIDER#<div class="bx-debug-content bx-debug-content-details">
			<?
				$j = 1;
				foreach($arQueries as $strSql=>$query)
				{
					?><div id="BX_DEBUG_INFO_<?=$i."_".$j?>" style="display:none">
					<b><?echo GetMessage("debug_info_query")?> <?echo $j?>:</b>
					<br /><br />
					<?
					$strSql = preg_replace("/[\\n\\r\\t\\s ]+/", " ", $strSql);
					$strSql = preg_replace("/^ +/", "", $strSql);
					$strSql = preg_replace("/ (INNER JOIN|OUTER JOIN|LEFT JOIN|SET|LIMIT) /i", "\n\\1 ", $strSql);
					$strSql = preg_replace("/(INSERT INTO [A-Z_0-1]+?)\\s/i", "\\1\n", $strSql);
					$strSql = preg_replace("/(INSERT INTO [A-Z_0-1]+?)([(])/i", "\\1\n\\2", $strSql);
					$strSql = preg_replace("/([\\s)])(VALUES)([\\s(])/i", "\\1\n\\2\n\\3", $strSql);
					$strSql = preg_replace("/ (FROM|WHERE|ORDER BY|GROUP BY|HAVING) /i", "\n\\1\n", $strSql);
						echo str_replace(
							array("\n"),
							array("<br />"),
							htmlspecialcharsbx($strSql)
						);
					?>
					<br /><br />
					<b><?echo GetMessage("debug_info_query_from")?></b>
					<?
					$k=1;
					foreach($query["CALLS"] as $call)
					{
						$back_trace = $call["TRACE"];

						if(is_array($back_trace))
						{
							foreach($back_trace as $n=>$tr)
							{
								?>
								<br /><br />
								<b>(<?echo $k.".".($n+1)?>)</b>
								<?
								echo $tr["file"].":".$tr["line"]."<br /><nobr>".htmlspecialcharsbx($tr["class"].$tr["type"].$tr["function"]);
								if($n == 0)
									echo "(...)</nobr>";
								else
									echo "</nobr>(".htmlspecialcharsbx(print_r($tr["args"], true)).")";
								if($n > 3)
									break;
							} //$back_trace
						}
						else //is_array($back_trace)
						{
							?>
							<br /><br />
							<b>(<?echo $k?>)</b> <?echo GetMessage("debug_info_query_from_unknown")?>
							<?
						} //is_array($back_trace)
						?>
						<br /><br />
						<?echo GetMessage("debug_info_query_time")?> <?echo round($call["TIME"], 5)?> <?echo GetMessage("debug_info_sec")?>
						<?
						$k++;
					} //$query["CALLS"]
					?></div>
					<?
					$j++;
				}; // $arQueries
				?>
			</div>
			<?
		} //if(count($arIncludeDebug["QUERIES"])>0)
		$obJSPopup->StartButtons();
		$obJSPopup->ShowStandardButtons(array('close'));

		/*************************************CACHE*********************************************/
		?>
		<script type="text/javascript">
			BX_DEBUG_INFO_CACHE_<?=$i?> = new BX.CDebugDialog();
		</script>
		<?
		$obJSPopup = new CJSPopupOnPage('', array());
		$obJSPopup->jsPopup = 'BX_DEBUG_INFO_CACHE_'.$i;
		$obJSPopup->StartDescription('bx-core-debug-info');
		?>
		<p><?echo GetMessage("debug_info_cache_size")?> <?=CFile::FormatSize($arIncludeDebug["CACHE_SIZE"], 0)?></p>
		<?
		$obJSPopup->StartContent(array('buffer' => true));
		if($arIncludeDebug["CACHE"] && !empty($arIncludeDebug["CACHE"]))
		{
			?>
			<div class="bx-debug-content bx-debug-content-table">
				<table id="cacheDebug<?=$i?>" cellpadding="2" cellspacing="0" border="0">
					<tr class="heading-sort">
						<td onclick="sortTable('cacheDebug<?=$i?>', 0)">&darr;&nbsp;</td>
						<td onclick="sortTable('cacheDebug<?=$i?>', 1)"><?echo GetMessage("debug_info_cache_table_func");?></td>
						<td onclick="sortTable('cacheDebug<?=$i?>', 2, true)"><?echo GetMessage("debug_info_cache_table_size");?></td>
						<td onclick="sortTable('cacheDebug', 3)"><?echo GetMessage("debug_info_cache_file_path");?></td>
					</tr>
					<?
					foreach($arIncludeDebug["CACHE"] as $j => $cacheDebug)
					{
						if (substr($cacheDebug["path"], 0, $DOCUMENT_ROOT_LEN) === $_SERVER["DOCUMENT_ROOT"])
							$path = '<a target="blank" href="/bitrix/admin/fileman_file_view.php?path='.urlencode(substr($cacheDebug["path"], $DOCUMENT_ROOT_LEN)).'&lang='.LANGUAGE_ID.'">'.htmlspecialcharsEx(substr($cacheDebug["path"], $DOCUMENT_ROOT_LEN)).'</a>';
						else
							$path = '&nbsp;';
					?>
					<tr class="cache-row">
						<td class="number"><?echo $j+1?></td>
						<td><a href="javascript:BX_DEBUG_INFO_CACHE_<?=$i?>.ShowDetails('BX_DEBUG_INFO_CACHE_<?=$i."_".$j?>')"><?echo $cacheDebug["callee_func"]?></a></td>
						<td class="number" sort="<?echo $cacheDebug["cache_size"]?>"><?=CFile::FormatSize($cacheDebug["cache_size"], 0)?></td>
						<td><?=$path?></td>
					</tr>
					<?
					}
					?>
				</table>
			</div>#DIVIDER#<div class="bx-debug-content bx-debug-content-details">
			<?
				foreach($arIncludeDebug["CACHE"] as $j => $cacheDebug)
				{
					?><div id="BX_DEBUG_INFO_CACHE_<?=$i?>_<?=$j?>" style="display:none">
					<b><?echo GetMessage("debug_info_query_from")?></b>
					<?
					$k=1;
					foreach($cacheDebug["TRACE"] as $n => $tr)
					{
						?>
						<br /><br />
						<b>(<?echo ($n + 1)?>)</b>
						<?
						echo $tr["file"].":".$tr["line"]."<br /><nobr>".htmlspecialcharsbx($tr["func"]);
						if($n == 0)
							echo "(...)</nobr>";
						else
							echo "</nobr>(".htmlspecialcharsbx(print_r($tr["args"], true)).")";
					} //$back_trace
					?></div>
					<?
				}; // $arQueries
				?>
			</div>
			<?
		} //if($arIncludeDebug["CACHE"])
		$obJSPopup->StartButtons();
		$obJSPopup->ShowStandardButtons(array('close'));
	} //$APPLICATION->arIncludeDebug
} //$bShowStat 2

if($bShowExtTime)
{
	$obJSPopup = new CJSPopupOnPage();
	$obJSPopup->jsPopup = 'jsDebugTimeWindow';
?>
<script type="text/javascript">
var jsDebugTimeWindow = new BX.CDebugDialog();
</script>
<div id="BX_DEBUG_TIME" class="bx-debug-window" style="z-index:99; width:660px !important;">
<?
	$obJSPopup->StartDescription('bx-core-debug-info');
?>
	<p><?echo GetMessage("debug_info_page")?> <?=$APPLICATION->GetCurPage()?></p>
	<p><?echo GetMessage("debug_info_comps_cache")?> <?if(COption::GetOptionString("main", "component_cache_on", "Y")=="Y") echo GetMessage("debug_info_comps_cache_on"); else echo "<a href=\"/bitrix/admin/cache.php\"><font class=\"errortext\">".GetMessage("debug_info_comps_cache_off")."</font></a>";?>.</p>
	<p><?
	if(\Bitrix\Main\Data\Cache::getShowCacheStat())
		echo GetMessage("debug_info_cache_size")." ",CFile::FormatSize(\Bitrix\Main\Diag\CacheTracker::getCacheStatBytes(), 0);
	else
		echo "&nbsp;";
	?></p>
<?
	$obJSPopup->StartContent(array('buffer' => true));
?>
	<div id="BX_DEBUG_TIME_1">
		<div class="bx-debug-content bx-debug-content-table">

<table cellpadding="0" cellspacing="0" border="0" width="100%">
	<tr class="heading">
		<td>&nbsp;</td>
		<td>&nbsp;</td>
		<td class="number" nowrap>
			<span><?echo GetMessage("debug_info_page_exec")?></span>
		</td>
		<td class="number" nowrap>
			<span><?echo GetMessage("debug_info_sec")?></span>
		</td>
		<?if($bShowComps):?>
			<td class="number" nowrap>
				<span><?echo GetMessage("debug_info_comps_exec")?></span>
			</td>
			<td class="number" nowrap>
				<span><?echo GetMessage("debug_info_sec")?></span>
			</td>
		<?endif;?>
		<?if($bShowStat):?>
			<td class="number" nowrap>
				<span><?echo GetMessage("debug_info_queries_exec")?></span>
			</td>
			<td class="number" nowrap>
				<span><?echo GetMessage("debug_info_sec")?></span>
			</td>
		<?endif;?>
		<td class="heading">&nbsp;</td>
	</tr>
	<tr class="heading heading-bottom">
		<td>&nbsp;</td>
		<td>
			<?if($bShowComps):?>
				<a style="font-weight:bold !important" href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_1')"><?echo GetMessage("debug_info_whole_page")?></a>
			<?else:?>
				<b><?echo GetMessage("debug_info_whole_page")?></b>
			<?endif?>
		</td>
		<td class="number" nowrap>
			<b><?echo number_format($PAGE/$PAGE*100, 2),"%"?></b>
		</td>
		<td class="number" nowrap>
			<b><?echo number_format($PAGE, 4)?></b>
		</td>
		<?if($bShowComps):?>
			<td class="number" nowrap>
				<b><?echo intval($arAreas["PAGE"]["TRACE"]["COMPONENT_COUNT"])?></b>
			</td>
			<td class="number" nowrap>
				<b><?echo number_format($arAreas["PAGE"]["TRACE"]["COMPONENT_TIME"], 4)?></b>
			</td>
		<?endif;?>
		<?if($bShowStat):?>
			<td class="number" nowrap>
				<b><?echo $arAreas["PAGE"]["TRACE"]["QUERY_COUNT"]+$arAreas["PAGE"]["TRACE"]["COMP_QUERY_COUNT"]?></b>
			</td>
			<td class="number" nowrap>
				<b><?echo number_format($arAreas["PAGE"]["TRACE"]["QUERY_TIME"]+$arAreas["PAGE"]["TRACE"]["COMP_QUERY_TIME"], 4)?></b>
			</td>
		<?endif;?>
		<td class="heading">&nbsp;</td>
	</tr>
	<tr valign="top">
		<td>&nbsp;</td>
		<td>
			<?if($bShowComps):?>
				<p><a style="font-weight:bold !important" href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_2')"><?echo GetMessage("debug_info_prolog")?></a></p>
				<p>
					&nbsp;&nbsp;<a href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_3')"><?echo GetMessage("debug_info_prolog_before")?></a><br>
					&nbsp;&nbsp;<a href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_4')"><?echo GetMessage("debug_info_agents")?></a><br>
					&nbsp;&nbsp;<a href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_5')"><?echo GetMessage("debug_info_prolog_after")?></a><br>
				</p>
			<?else:?>
				<p><b><?echo GetMessage("debug_info_prolog")?></b></p>
				<p>
					&nbsp;&nbsp;<?echo GetMessage("debug_info_prolog_before")?><br>
					&nbsp;&nbsp;<?echo GetMessage("debug_info_agents")?><br>
					&nbsp;&nbsp;<?echo GetMessage("debug_info_prolog_after")?><br>
				</p>
			<?endif?>
		</td>
		<td class="number" nowrap>
			<p><b><?echo number_format($PROLOG/$PAGE*100, 2),"%"?></b></p>
			<p>
				<?echo number_format($PROLOG_BEFORE/$PAGE*100, 2),"%"?><br>
				<?echo number_format($AGENTS/$PAGE*100, 2),"%"?><br>
				<?echo number_format($PROLOG_AFTER/$PAGE*100, 2),"%"?><br>
			</p>
		</td>
		<td class="number" nowrap>
			<p><b><?echo number_format($PROLOG, 4)?></b></p>
			<p>
				<?echo number_format($PROLOG_BEFORE, 4)?><br>
				<?echo number_format($AGENTS, 4)?><br>
				<?echo number_format($PROLOG_AFTER, 4)?><br>
			</p>
		</td>
		<?if($bShowComps):?>
			<td class="number" nowrap>
				<p><b><?echo intval($arAreas["PROLOG"]["TRACE"]["COMPONENT_COUNT"])?></b></p>
				<p>
					<?echo intval($arAreas["PROLOG_BEFORE"]["TRACE"]["COMPONENT_COUNT"])?><br>
					<?echo intval($arAreas["AGENTS"]["TRACE"]["COMPONENT_COUNT"])?><br>
					<?echo intval($arAreas["PROLOG_AFTER"]["TRACE"]["COMPONENT_COUNT"])?><br>
				</p>
			</td>
			<td class="number" nowrap>
				<p><b><?echo number_format($arAreas["PROLOG"]["TRACE"]["COMPONENT_TIME"], 4)?></b></p>
				<p>
					<?echo number_format($arAreas["PROLOG_BEFORE"]["TRACE"]["COMPONENT_TIME"], 4)?><br>
					<?echo number_format($arAreas["AGENTS"]["TRACE"]["COMPONENT_TIME"], 4)?><br>
					<?echo number_format($arAreas["PROLOG_AFTER"]["TRACE"]["COMPONENT_TIME"], 4)?><br>
				</p>
			</td>
		<?endif;?>
		<?if($bShowStat):?>
			<td class="number" nowrap>
				<p><b><?echo $arAreas["PROLOG"]["TRACE"]["QUERY_COUNT"]+$arAreas["PROLOG"]["TRACE"]["COMP_QUERY_COUNT"]?></b></p>
				<p>
					<?echo $arAreas["PROLOG_BEFORE"]["TRACE"]["QUERY_COUNT"]+$arAreas["PROLOG_BEFORE"]["TRACE"]["COMP_QUERY_COUNT"]?><br>
					<?echo $arAreas["AGENTS"]["TRACE"]["QUERY_COUNT"]+$arAreas["AGENTS"]["TRACE"]["COMP_QUERY_COUNT"]?><br>
					<?echo $arAreas["PROLOG_AFTER"]["TRACE"]["QUERY_COUNT"]+$arAreas["PROLOG_AFTER"]["TRACE"]["COMP_QUERY_COUNT"]?><br>
				</p>
			</td>
			<td class="number" nowrap>
				<p><b><?echo number_format($arAreas["PROLOG"]["TRACE"]["QUERY_TIME"]+$arAreas["PROLOG"]["TRACE"]["COMP_QUERY_TIME"], 4)?></b></p>
				<p>
					<?echo number_format($arAreas["PROLOG_BEFORE"]["TRACE"]["QUERY_TIME"]+$arAreas["PROLOG_BEFORE"]["TRACE"]["COMP_QUERY_TIME"], 4)?><br>
					<?echo number_format($arAreas["AGENTS"]["TRACE"]["QUERY_TIME"]+$arAreas["AGENTS"]["TRACE"]["COMP_QUERY_TIME"], 4)?><br>
					<?echo number_format($arAreas["PROLOG_AFTER"]["TRACE"]["QUERY_TIME"]+$arAreas["PROLOG_AFTER"]["TRACE"]["COMP_QUERY_TIME"], 4)?><br>
				</p>
			</td>
		<?endif;?>
		<td>&nbsp;</td>
	</tr>
	<tr valign="top">
		<td>&nbsp;</td>
		<td>
			<?if($bShowComps):?>
				<p><a style="font-weight:bold !important" href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_6')"><?echo GetMessage("debug_info_work_area")?></a></p>
			<?else:?>
				<p><b><?echo GetMessage("debug_info_work_area")?></b></p>
			<?endif?>
		</td>
		<td class="number" nowrap>
			<p><b><?echo number_format($WORK_AREA/$PAGE*100, 2),"%"?></b></p>
		</td>
		<td class="number" nowrap>
			<p><b><?echo number_format($WORK_AREA, 4)?></b></p>
		</td>
		<?if($bShowComps):?>
			<td class="number" nowrap>
				<b><?echo intval($arAreas["WORK_AREA"]["TRACE"]["COMPONENT_COUNT"])?></b>
			</td>
			<td class="number" nowrap>
				<b><?echo number_format($arAreas["WORK_AREA"]["TRACE"]["COMPONENT_TIME"], 4)?></b>
			</td>
		<?endif;?>
		<?if($bShowStat):?>
			<td class="number" nowrap>
				<p><b><?echo $arAreas["WORK_AREA"]["TRACE"]["QUERY_COUNT"]+$arAreas["WORK_AREA"]["TRACE"]["COMP_QUERY_COUNT"]?></b></p>
			</td>
			<td class="number" nowrap>
				<p><b><?echo number_format($arAreas["WORK_AREA"]["TRACE"]["QUERY_TIME"]+$arAreas["WORK_AREA"]["TRACE"]["COMP_QUERY_TIME"], 4)?></b></p>
			</td>
		<?endif;?>
		<td>&nbsp;</td>
	</tr>
	<tr valign="top">
		<td>&nbsp;</td>
		<td>
			<?if($bShowComps):?>
				<p><a style="font-weight:bold !important" href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_7')"><?echo GetMessage("debug_info_epilog")?></a></p>
				<p>
					&nbsp;&nbsp;<a href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_8')"><?echo GetMessage("debug_info_epilog_before")?></a><br>
					&nbsp;&nbsp;<a href="javascript:jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_9')"><?echo GetMessage("debug_info_epilog_after")?></a><br>
				</p>
			<?else:?>
				<p><b><?echo GetMessage("debug_info_epilog")?></b></p>
				<p>
					&nbsp;&nbsp;<?echo GetMessage("debug_info_epilog_before")?><br>
					&nbsp;&nbsp;<?echo GetMessage("debug_info_epilog_after")?><br>
				</p>
			<?endif?>
		</td>
		<td class="number" nowrap>
			<p><b><?echo number_format($EPILOG/$PAGE*100, 2),"%"?></b></p>
			<p>
				<?echo number_format($EPILOG_BEFORE/$PAGE*100, 2),"%"?><br>
				<?echo number_format($EPILOG_AFTER/$PAGE*100, 2),"%"?><br>
			</p>
		</td>
		<td class="number" nowrap>
			<p><b><?echo number_format($EPILOG, 4)?></b></p>
			<p>
				<?echo number_format($EPILOG_BEFORE, 4)?><br>
				<?echo number_format($EPILOG_AFTER, 4)?><br>
			</p>
		</td>
		<?if($bShowComps):?>
			<td class="number" nowrap>
				<p><b><?echo intval($arAreas["EPILOG"]["TRACE"]["COMPONENT_COUNT"])?></b></p>
				<p>
					<?echo intval($arAreas["EPILOG_BEFORE"]["TRACE"]["COMPONENT_COUNT"])?><br>
					<?echo intval($arAreas["EPILOG_AFTER"]["TRACE"]["COMPONENT_COUNT"])?><br>
				</p>
			</td>
			<td class="number" nowrap>
				<p><b><?echo number_format($arAreas["EPILOG"]["TRACE"]["COMPONENT_TIME"], 4)?></b></p>
				<p>
					<?echo number_format($arAreas["EPILOG_BEFORE"]["TRACE"]["COMPONENT_TIME"], 4)?><br>
					<?echo number_format($arAreas["EPILOG_AFTER"]["TRACE"]["COMPONENT_TIME"], 4)?><br>
				</p>
			</td>
		<?endif;?>
		<?if($bShowStat):?>
			<td class="number" nowrap>
				<p><b><?echo $arAreas["EPILOG"]["TRACE"]["QUERY_COUNT"]+$arAreas["EPILOG"]["TRACE"]["COMP_QUERY_COUNT"]?></b></p>
				<p>
					<?echo $arAreas["EPILOG_BEFORE"]["TRACE"]["QUERY_COUNT"]+$arAreas["EPILOG_BEFORE"]["TRACE"]["COMP_QUERY_COUNT"]?><br>
					<?echo $arAreas["EPILOG_AFTER"]["TRACE"]["QUERY_COUNT"]+$arAreas["EPILOG_AFTER"]["TRACE"]["COMP_QUERY_COUNT"]?><br>
				</p>
			</td>
			<td class="number" nowrap>
				<p><b><?echo number_format($arAreas["EPILOG"]["TRACE"]["QUERY_TIME"]+$arAreas["EPILOG"]["TRACE"]["COMP_QUERY_TIME"], 4)?></b></p>
				<p>
					<?echo number_format($arAreas["EPILOG_BEFORE"]["TRACE"]["QUERY_TIME"]+$arAreas["EPILOG_BEFORE"]["TRACE"]["COMP_QUERY_TIME"], 4)?><br>
					<?echo number_format($arAreas["EPILOG_AFTER"]["TRACE"]["QUERY_TIME"]+$arAreas["EPILOG_AFTER"]["TRACE"]["COMP_QUERY_TIME"], 4)?><br>
				</p>
			</td>
		<?endif;?>
		<td>&nbsp;</td>
	</tr>
</table>

		</div>
	</div>#DIVIDER#<?if($bShowComps):?><div class="bx-debug-content bx-debug-content-table">
			<?foreach($arAreas as $id => $arArea):?>
			<div id="BX_DEBUG_TIME_1_<?echo $arArea["NUM"]?>" style="display:none">
				<table cellpadding="0" cellspacing="0" border="0" width="100%">
				<?
				$tim = 0;
				foreach($APPLICATION->arIncludeDebug as $i=>$arIncludeDebug)
				{
					if(isset($arIncludeDebug["REL_PATH"]) && in_array($arIncludeDebug["BX_STATE"], $arArea["FLT"]))
					{
						$tim += $arIncludeDebug["TIME"];
					}
				}
				if($tim > $arArea["TIME"]) $tim = $arArea["TIME"];
				?>
					<tr>
						<td class="number" valign="top">0</td>
						<td>
						<?if($bShowStat):?>
							<a title="<?echo GetMessage("debug_info_query_title")?>" href="javascript:BX_DEBUG_INFO_<?echo $arArea["IND"]?>.Show(); BX_DEBUG_INFO_<?echo $arArea['IND']?>.ShowDetails('BX_DEBUG_INFO_<?echo $arArea['IND']?>_1');"><?echo GetMessage("debug_info_raw_code")?></a>
						<?else:?>
							<?echo GetMessage("debug_info_raw_code")?>
						<?endif?>
						</td>
						<td>&nbsp;</td>
						<td class="number">&nbsp;<?
							if($arArea["TRACE"]["CACHE_SIZE"])
								echo CFile::FormatSize($arArea["TRACE"]["CACHE_SIZE"],0);
						?></td>
						<td class="number"><?if($arArea["TIME"] > 0):?><?echo number_format((1-$tim/$arArea["TIME"])*100, 2)?>%<?endif?></td>
						<td class="number"><?echo number_format($arArea["TIME"] - $tim, 4)?> <?echo GetMessage("debug_info_sec")?></td>
						<td class="number"><?echo intval($arArea["TRACE"]["QUERY_COUNT"])?> <?echo GetMessage("debug_info_query_short")?></td>
						<td class="number"><?echo number_format($arArea["TRACE"]["QUERY_TIME"], 4)?> <?echo GetMessage("debug_info_sec")?></td>
					</tr>
				<?$j=1;$k=1;foreach($APPLICATION->arIncludeDebug as $i=>$arIncludeDebug):?>
					<?if(isset($arIncludeDebug["REL_PATH"]) && in_array($arIncludeDebug["BX_STATE"], $arArea["FLT"])):?>
					<tr>
						<td class="number" valign="top"><?echo $k?></td>
						<td>
						<?if($arIncludeDebug["LEVEL"] > 0) echo str_repeat("&nbsp;&nbsp;", $arIncludeDebug["LEVEL"]);?>
						<?if($bShowStat):?>
							<a title="<?echo GetMessage("debug_info_query_title")?>" href="javascript:BX_DEBUG_INFO_<?echo $i?>.Show(); BX_DEBUG_INFO_<?echo $i?>.ShowDetails('BX_DEBUG_INFO_<?echo $i?>_1');"><?echo htmlspecialcharsbx($arIncludeDebug["REL_PATH"])?></a>
						<?else:?>
							<?echo htmlspecialcharsbx($arIncludeDebug["REL_PATH"])?>
						<?endif?>
						</td>
						<td>&nbsp;<?
							switch($arIncludeDebug["CACHE_TYPE"])
							{
								case "N": echo GetMessage("debug_info_cache_off"); break;
								case "Y": echo GetMessage("debug_info_cache_on"); break;
								default: echo GetMessage("debug_info_cache_auto"); break;
							}
						?></td>
						<td class="number" nowrap>&nbsp;<?
							if($arIncludeDebug["CACHE_SIZE"])
								echo CFile::FormatSize($arIncludeDebug["CACHE_SIZE"],0);
						?></td>
						<td class="number" nowrap><?if($arArea["TIME"] > 0):?><?echo number_format($arIncludeDebug["TIME"]/$arArea["TIME"]*100, 2)?>%<?endif?></td>
						<td class="number" nowrap><?echo number_format($arIncludeDebug["TIME"], 4)?> <?echo GetMessage("debug_info_sec")?></td>
						<td class="number" nowrap><?echo intval($arIncludeDebug["QUERY_COUNT"])?> <?echo GetMessage("debug_info_query_short")?></td>
						<td class="number" nowrap><?echo number_format($arIncludeDebug["QUERY_TIME"], 4)?> <?echo GetMessage("debug_info_sec")?></td>
					</tr>
					<?$k++;endif;?>
				<?$j++;endforeach;?>
				</table>
			</div>
			<?endforeach;?>
		</div>
		<?endif;?>
<?
	$obJSPopup->StartButtons();
	$obJSPopup->ShowStandardButtons(array('close'));
?>
</div>
<?
	if(
		$_GET["show_sql_stat"] === "Y"
		&& $_GET["show_page_exec_time"] === "Y"
		&& $_GET["show_sql_stat_immediate"] === "Y"
		&& preg_match("#/admin/perfmon_hit_list.php#", $_SERVER["HTTP_REFERER"])
	)
		echo "<script>BX.ready(function() {jsDebugTimeWindow.Show(); jsDebugTimeWindow.ShowDetails('BX_DEBUG_TIME_1_1');});</script>";
}
?>admin_tabengine.php000064400000004524147732346240010402 0ustar00<?php
/**
 * Bitrix Framework
 * @package bitrix
 * @subpackage main
 * @copyright 2001-2016 Bitrix
 */

class CAdminTabEngine
{
	var $name;
	var $bInited = False;
	var $arEngines = array();
	var $arArgs = array();
	var $bVarsFromForm = False;

	public function __construct($name, $arArgs = array())
	{
		$this->bInited = False;
		$this->name = $name;
		$this->arEngines = array();
		$this->arArgs = $arArgs;

		foreach (GetModuleEvents("main", $this->name, true) as $arEvent)
		{
			$res = ExecuteModuleEventEx($arEvent, array($this->arArgs));
			if (is_array($res))
				$this->arEngines[$res["TABSET"]] = $res;
			$this->bInited = True;
		}
	}

	function SetErrorState($bVarsFromForm = False)
	{
		$this->bVarsFromForm = $bVarsFromForm;
	}

	function SetArgs($arArgs = array())
	{
		$this->arArgs = $arArgs;
	}

	function Check()
	{
		if (!$this->bInited)
			return True;

		$result = True;

		foreach ($this->arEngines as $value)
		{
			if (array_key_exists("Check", $value))
			{
				$resultTmp = call_user_func_array($value["Check"], array($this->arArgs));
				if ($result && !$resultTmp)
					$result = False;
			}
		}

		return $result;
	}

	function Action()
	{
		if (!$this->bInited)
			return True;

		$result = True;

		foreach ($this->arEngines as $value)
		{
			if (array_key_exists("Action", $value))
			{
				$resultTmp = call_user_func_array($value["Action"], array($this->arArgs));
				if ($result && !$resultTmp)
					$result = False;
			}
		}

		return $result;
	}

	function GetTabs()
	{
		if (!$this->bInited)
			return False;

		$arTabs = array();
		foreach ($this->arEngines as $key => $value)
		{
			if (array_key_exists("GetTabs", $value))
			{
				$arTabsTmp = call_user_func_array($value["GetTabs"], array($this->arArgs));
				if (is_array($arTabsTmp))
				{
					foreach ($arTabsTmp as $key1 => $value1)
					{
						$arTabsTmp[$key1]["DIV"] = $key."_".$arTabsTmp[$key1]["DIV"];
					}

					$arTabs = array_merge($arTabs, $arTabsTmp);
				}
			}
		}

		return $arTabs;
	}

	function ShowTab($divName)
	{
		if (!$this->bInited)
			return False;

		foreach ($this->arEngines as $key => $value)
		{
			if (SubStr($divName, 0, StrLen($key."_")) == $key."_")
			{
				if (array_key_exists("ShowTab", $value))
					call_user_func_array($value["ShowTab"], array(SubStr($divName, StrLen($key."_")), $this->arArgs, $this->bVarsFromForm));
			}
		}
		return null;
	}
}
404.php000064400000001527147732346240005605 0ustar00<?
if($_SERVER["REDIRECT_STATUS"]=="404")
	define("ERROR_404","Y");

define('BX_ADMIN_SECTION_404', 'Y');

if (($pos = strpos($_SERVER["REQUEST_URI"], "?")) !== false)
{
	$params = substr($_SERVER["REQUEST_URI"], $pos+1);
	parse_str($params, $_GET);
	$GLOBALS += $_GET;
	$HTTP_GET_VARS = $_GET;
}

require_once(dirname(__FILE__)."/../include/prolog_admin_before.php");
IncludeModuleLangFile(__FILE__);

$APPLICATION->SetTitle(GetMessage("404_title"));
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
?>

<div class="adm-404-block">
	<div class="adm-404-text1">
		<?echo GetMessage("404_header")?>
	</div>
	<div class="adm-404-text2"><?echo GetMessage("404_message")?></div>
	<div class="adm-404-footer"></div>
</div>

<?
require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin.php");
?>epilog_main_admin.php000064400000010271147732346240010725 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

include($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/interface/lang_files.php");
?>
<?

$isSidePanel = (isset($_REQUEST["IFRAME"]) && $_REQUEST["IFRAME"] === "Y");
//End of Content

if(COption::GetOptionString("main", "update_devsrv", "") == "Y")
{
	?><br><br><?
	echo BeginNote('style="position: relative; top: -15px;"');
	?><span class="required"><?echo GetMessage("DEVSERVER_ADMIN_MESSAGE");?></span><?
	echo EndNote();
}
?>
				</div><?//adm-workarea?>
			</td><?//adm-workarea-wrap?>
		</tr>
		<?if (!$isSidePanel):?>
		<tr class="adm-footer-wrap">
			<td class="adm-left-side-wrap"></td>
			<td class="adm-workarea-wrap">
<?
//Footer
$vendor = COption::GetOptionString("main", "vendor", "1c_bitrix");

//wizard customization file
if(isset($bxProductConfig["admin"]["copyright"]))
	$sCopyright = $bxProductConfig["admin"]["copyright"];
else
	$sCopyright = GetMessage("EPILOG_ADMIN_POWER").' <a href="'.GetMessage("EPILOG_ADMIN_URL_PRODUCT_".$vendor).'">'.GetMessage("EPILOG_ADMIN_SM_".$vendor).'#VERSION#</a>. '.GetMessage("EPILOG_ADMIN_COPY_".$vendor);
$sVer = ($GLOBALS['USER']->CanDoOperation('view_other_settings')? " ".SM_VERSION : "");
$sCopyright = str_replace("#VERSION#", $sVer, $sCopyright);

if(isset($bxProductConfig["admin"]["links"]))
	$sLinks = $bxProductConfig["admin"]["links"];
else
	$sLinks = '<a href="'.GetMessage("EPILOG_ADMIN_URL_MAIN_".$vendor).'">'.GetMessage("EPILOG_ADMIN_URL_MAIN_TEXT_".$vendor).'</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="'.GetMessage("EPILOG_ADMIN_URL_SUPPORT_".$vendor).'" class="adm-main-support-link">'.GetMessage("epilog_support_link").'</a>';
?>
			<table cellpadding="0" cellspacing="0" border="0" width="100%">
				<tr>
					<td><?echo $sCopyright?></td>
					<td align="right"><?if(($siteSupport = getLocalPath("php_interface/this_site_support.php", BX_PERSONAL_ROOT)) !== false):?><?include($_SERVER["DOCUMENT_ROOT"].$siteSupport);?><?else:?><?echo $sLinks?><?endif;?></td>
				</tr>
			</table>
<?
//End of Footer
?>
			</td>
		</tr>
		<?endif;?>
	</table>
	<div id="fav_cont_item" class="adm-favorites-main" style="display:none;">
		<div class="adm-favorites-alignment">
			<div class="adm-favorites-center" id="fav_dest_item">
				<div id="fav_text_item" style="display: inline-block;">
					<div class="adm-favorites-text"><?=GetMessage('ADMIN_FAV_ADD')?></div>
					<div class="adm-favorites-description"><?=GetMessage('ADMIN_FAV_HINT')?></div>
				</div>
				<div id="fav_text_finish_item" style="display: none;">
					<div class="adm-favorites-text"><?=GetMessage('ADMIN_FAV_ADD_SUCCESS')?></div>
					<div class="adm-favorites-description"><a class="adm-favorites-description_link" href="javascript:void(0);" onclick="BX.adminMenu.showFavorites(this);"><?=GetMessage('ADMIN_FAV_GOTO')?></a></div>
				</div>
				<div id="fav_text_error_item" style="display: none;">
					<div class="adm-favorites-text"><?=GetMessage('ADMIN_FAV_ADD_ERROR')?></div>
				</div>
				<div class="adm-favorites-center-border-2"></div>
				<div class="adm-favorites-center-border-1"></div>
				<div class="adm-favorites-check-icon" id="fav_icon_finish_item"></div>
			</div>
		</div>
	</div>
	<div id="fav_cont_fav" class="adm-favorites-main remove-favorites-main" style="display:none;">
		<div class="adm-favorites-alignment">
			<div class="adm-favorites-center" id="fav_dest_fav">
				<div id="fav_text_fav" style="display: inline-block;">
					<div class="adm-favorites-text"><?=GetMessage('ADMIN_FAV_DEL')?></div>
					<div class="adm-favorites-description"><?=GetMessage('ADMIN_FAV_HINT')?></div>
				</div>
				<div id="fav_text_finish_fav" style="display: none;">
					<div class="adm-favorites-text"><?=GetMessage('ADMIN_FAV_DEL_SUCCESS')?></div>
				</div>
				<div id="fav_text_error_fav" style="display: none;">
					<div class="adm-favorites-text"><?=GetMessage('ADMIN_FAV_DEL_ERROR')?></div>
				</div>
				<div class="adm-favorites-center-border-2"></div>
				<div class="adm-favorites-center-border-1"></div>
				<div class="adm-favorites-check-icon" id="fav_icon_finish_fav"></div>
			</div>
		</div>
	</div>
<?
if (!defined('ADMIN_SECTION_LOAD_AUTH') || !ADMIN_SECTION_LOAD_AUTH):
?>
</body>
</html>
<?
endif;
?>
epilog_jspopup_admin.php000064400000000335147732346240011501 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

include($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/interface/lang_files.php");
?>
</div>
<?
ob_end_flush();
?>desktop_menu.php000064400000002730147732346240007770 0ustar00<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
IncludeModuleLangFile(__FILE__);

if ($USER->IsAuthorized())
{
	$DESKTOP_CURRENT = $APPLICATION->GetCurPage(true) == "/bitrix/admin/index.php" ? intval($_REQUEST['dt_page']) : -1;
	$arUserOptions = CUserOptions::GetOption("intranet", "~gadgets_admin_index", array(), false);
	if(!is_array($arUserOptions))
		$arUserOptions = Array();

	if (count($arUserOptions) > 0):
		?><div id="adm-submenu-desktop" class="adm-submenu-items-wrap adm-submenu-desktop" style="">
			<div class="adm-submenu-items-block"><?
				foreach ($arUserOptions as $DESKTOP_ID => $arUserOption):
					$desktop_className = 'adm-submenu-main-desktop'.($DESKTOP_ID == $DESKTOP_CURRENT ? ' adm-submenu-item-desktop-active' : '');
					?><a href="/bitrix/admin/?dt_page=<?=$DESKTOP_ID?>" class="adm-submenu-item<?=$desktop_className ? ' '.$desktop_className : ''?>">
						<div class="adm-submenu-item-icon"></div>
						<div class="adm-submenu-item-text"><?=strlen($arUserOption["NAME"]) > 0 ? htmlspecialcharsbx($arUserOption["NAME"]) : str_replace('#NUM#', $DESKTOP_ID + 1, GetMessage('DESKTOP_DEFAULT_NAME'));?></div>
					</a><?
				endforeach;
				?><div class="adm-submenu-add-desktop" onclick="BX.adminPanel.addDesktop();">
					<span class="adm-submenu-add-desktop-icon"></span><span class="adm-submenu-add-desktop-text"><?=GetMessage('DESKTOP_ADD')?></span>
				</div>
			</div>
			<div class="adm-submenu-separator"></div>
		</div><?
	endif;
}
?>hot_keys_act.php000064400000005706147732346240007755 0ustar00<?
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");

$hkInstance = CHotKeys::GetInstance();
$uid=$USER->GetID();

if($USER->IsAuthorized() && check_bitrix_sessid())
{
	$res = false;

	switch ($_REQUEST["hkaction"])
	{
		case  'add':

				$arFields = array(
								"KEYS_STRING"=>rawurldecode($_REQUEST["KEYS_STRING"]),
								"CODE_ID"=>$_REQUEST["CODE_ID"],
								"USER_ID"=>$uid
								);

				$res = $hkInstance->Add($arFields);
				break;

		case  'update':

				if($hkInstance->GetUIDbyHID($_REQUEST["ID"])==$uid)
					$res = $hkInstance->Update($_REQUEST["ID"],array( "KEYS_STRING"=>rawurldecode($_REQUEST["KEYS_STRING"]) ));

				break;

		case  'delete':

				if($hkInstance->GetUIDbyHID($_REQUEST["ID"])==$uid)
					$res = $hkInstance->Delete($_REQUEST["ID"]);

				break;

		case  'delete_all':

				$res=0;
				$listRes=$hkInstance->GetList(array(),array( "USER_ID" => $uid ));
				while($arHK=$listRes->Fetch())
					$res += $hkInstance->Delete($arHK["ID"]);

				break;

		case  'set_default':

				$sdRes = $hkInstance->SetDefault($uid);
				if($sdRes)
				{
					$res="";
					$listRes=$hkInstance->GetList(array(),array( "USER_ID" => $uid ));
					while($arHK=$listRes->Fetch())
						$res.=$arHK["CODE_ID"]."::".$arHK["ID"]."::".$arHK["KEYS_STRING"].";;";
				}

				break;

		case  'export':

				$tmpExportFile = $hkInstance->Export();

				if($tmpExportFile)
					if(file_exists($tmpExportFile))
						if(filesize($tmpExportFile)>0)
						{
							header('Content-type: application/force-download');
							header('Content-Disposition: attachment; filename="'.CHotKeys::$ExpImpFileName.'"');
							$res = file_get_contents($tmpExportFile);
							break;
						}

				$res='
				<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
				<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.LANGUAGE_ID.'" lang="'.LANGUAGE_ID.'">
				<body>
				<script>alert("'.GetMessage("HK_EXP_FALSE").'");
				window.close();
				</script>
				</body></html>';
				break;

		case  'import':

				if(!$_FILES['bx_hk_filename']['name'] || !$_FILES['bx_hk_filename']['size'])
				{
					$res='<script type="text/javascript">window.parent.BXHotKeys.OnImportResponse(0);</script>';
					break;
				}

				$numImported = 0;

				$tmpDir = CTempFile::GetDirectoryName();
				CheckDirPath($tmpDir);

				$name = $tmpDir.basename($_FILES['bx_hk_filename']['name']);

				if(move_uploaded_file($_FILES['bx_hk_filename']['tmp_name'], $tmpDir.CHotKeys::$ExpImpFileName))
					$numImported = $hkInstance->Import($tmpDir.CHotKeys::$ExpImpFileName,$uid);

				$res='<script type="text/javascript">window.parent.BXHotKeys.OnImportResponse("'.$numImported.'");</script>';

				break;
	}

	echo $res;
}

require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/epilog_admin_after.php");
?>