]*>#i", "\r\n", $str);
$str = preg_replace("#<[/]{0,1}(font|div|span)[^>]*>#i", "", $str);
//replace lists
$str = preg_replace("#
]*>#i", "\r\n", $str);
$str = preg_replace("#- ]*>#i", "\r\n - ", $str);
//delete by function parameter
foreach ($aDelete as $del_reg)
{
$str = preg_replace($del_reg, "", $str);
}
//replace images
$str = preg_replace("/(
]*?src\\s*=\\s*)([\"']?)(\\/.*?)(\\2)(\\s.+?>|\\s*>)/is", "[" . chr(1) . $strSiteUrl . "\\3" . chr(1) . "] ", $str);
$str = preg_replace("/(
]*?src\\s*=\\s*)([\"']?)(.*?)(\\2)(\\s.+?>|\\s*>)/is", "[" . chr(1) . "\\3" . chr(1) . "] ", $str);
//replace links
$str = preg_replace("/(]*?href\\s*=\\s*)([\"']?)(\\/.*?)(\\2)(.*?>)(.*?)<\\/a>/is", "\\6 [" . chr(1) . $strSiteUrl . "\\3" . chr(1) . "] ", $str);
$str = preg_replace("/(]*?href\\s*=\\s*)([\"']?)(.*?)(\\2)(.*?>)(.*?)<\\/a>/is", "\\6 [" . chr(1) . "\\3" . chr(1) . "] ", $str);
//replace
$str = preg_replace("#
]*>#i", "\r\n", $str);
//replace
$str = preg_replace("#
]*>#i", "\r\n\r\n", $str);
//replace
$str = preg_replace("#
]*>#i", "\r\n----------------------\r\n", $str);
//replace tables
$str = preg_replace("#<[/]{0,1}(thead|tbody)[^>]*>#i", "", $str);
$str = preg_replace("#<([/]{0,1})th[^>]*>#i", "<\\1td>", $str);
$str = preg_replace("##i", "\t", $str);
$str = preg_replace("##i", "\r\n", $str);
$str = preg_replace("#]*>#i", "\r\n", $str);
$str = preg_replace("#\r\n[ ]+#", "\r\n", $str);
//remove all tags
$str = preg_replace("#<[/]{0,1}[^>]+>#i", "", $str);
$str = preg_replace("#[ ]+ #", " ", $str);
$str = str_replace("\t", " ", $str);
//wrap long lines
if ($maxlen > 0)
{
$str = preg_replace("#(^|[\\r\\n])([^\\n\\r]{" . intval($maxlen) . "}[^ \\r\\n]*[\\] ])([^\\r])#", "\\1\\2\r\n\\3", $str);
}
$str = str_replace(chr(1), " ", $str);
return trim($str);
}
function FormatText($strText, $strTextType = "text")
{
if (strtolower($strTextType) == "html")
{
return $strText;
}
return TxtToHtml($strText);
}
function htmlspecialcharsEx($str)
{
static $search = ["&", "<", ">", """, """, """, "'", "'", "<", ">", "\""];
static $replace = ["&", "<", ">", """, """, """, "'", "'", "<", ">", """];
return Text\StringHelper::str_replace($search, $replace, $str);
}
function htmlspecialcharsback($str)
{
static $search = ["<", ">", """, "'", "&"];
static $replace = ["<", ">", "\"", "'", "&"];
return Text\StringHelper::str_replace($search, $replace, $str);
}
function htmlspecialcharsbx($string, $flags = ENT_COMPAT, $doubleEncode = true)
{
//function for php 5.4 where default encoding is UTF-8
return htmlspecialchars((string)$string, $flags, "UTF-8", $doubleEncode);
}
function CheckDirPath($path)
{
//remove file name
if (!str_ends_with($path, "/"))
{
$p = mb_strrpos($path, "/");
$path = mb_substr($path, 0, $p);
}
$path = rtrim($path, "/");
if ($path == "")
{
//current folder always exists
return true;
}
if (!file_exists($path))
{
return mkdir($path, BX_DIR_PERMISSIONS, true);
}
return is_dir($path);
}
function CopyDirFiles($path_from, $path_to, $ReWrite = true, $Recursive = false, $bDeleteAfterCopy = false, $strExclude = "")
{
if (mb_strpos($path_to . "/", $path_from . "/") === 0 || realpath($path_to) === realpath($path_from))
{
return false;
}
if (is_dir($path_from))
{
CheckDirPath($path_to . "/");
}
elseif (is_file($path_from))
{
$p = bxstrrpos($path_to, "/");
$path_to_dir = mb_substr($path_to, 0, $p);
CheckDirPath($path_to_dir . "/");
if (file_exists($path_to) && !$ReWrite)
{
return false;
}
@copy($path_from, $path_to);
if (is_file($path_to))
{
@chmod($path_to, BX_FILE_PERMISSIONS);
}
if ($bDeleteAfterCopy)
{
@unlink($path_from);
}
return true;
}
else
{
return true;
}
if ($handle = @opendir($path_from))
{
while (($file = readdir($handle)) !== false)
{
if ($file == "." || $file == "..")
{
continue;
}
if ($strExclude <> '' && str_starts_with($file, $strExclude))
{
continue;
}
if (is_dir($path_from . "/" . $file) && $Recursive)
{
CopyDirFiles($path_from . "/" . $file, $path_to . "/" . $file, $ReWrite, $Recursive, $bDeleteAfterCopy, $strExclude);
if ($bDeleteAfterCopy)
{
@rmdir($path_from . "/" . $file);
}
}
elseif (is_file($path_from . "/" . $file))
{
if (file_exists($path_to . "/" . $file) && !$ReWrite)
{
continue;
}
@copy($path_from . "/" . $file, $path_to . "/" . $file);
@chmod($path_to . "/" . $file, BX_FILE_PERMISSIONS);
if ($bDeleteAfterCopy)
{
@unlink($path_from . "/" . $file);
}
}
}
@closedir($handle);
if ($bDeleteAfterCopy)
{
@rmdir($path_from);
}
return true;
}
return false;
}
function DeleteDirFilesEx($path, $root = null)
{
if ($path == '' || $path == '/')
{
return false;
}
if ($root === null)
{
$root = $_SERVER["DOCUMENT_ROOT"];
}
$full_path = $root . "/" . $path;
$full_path = preg_replace("#[\\\\\\/]+#", "/", $full_path);
$f = true;
if (is_file($full_path) || is_link($full_path))
{
if (@unlink($full_path))
{
return true;
}
return false;
}
elseif (is_dir($full_path))
{
if ($handle = opendir($full_path))
{
while (($file = readdir($handle)) !== false)
{
if ($file == "." || $file == "..")
{
continue;
}
if (!DeleteDirFilesEx($path . "/" . $file, $root))
{
$f = false;
}
}
closedir($handle);
}
if (!@rmdir($full_path))
{
return false;
}
return $f;
}
return false;
}
function DeleteDirFiles($frDir, $toDir, $arExept = [])
{
if (is_dir($frDir))
{
$d = dir($frDir);
while ($entry = $d->read())
{
if ($entry == "." || $entry == "..")
{
continue;
}
if (in_array($entry, $arExept))
{
continue;
}
@unlink($toDir . "/" . $entry);
}
$d->close();
}
}
function RewriteFile($abs_path, $strContent)
{
CheckDirPath($abs_path);
if (file_exists($abs_path) && !is_writable($abs_path))
{
@chmod($abs_path, BX_FILE_PERMISSIONS);
}
$fd = fopen($abs_path, "wb");
if (!fwrite($fd, $strContent))
{
return false;
}
@chmod($abs_path, BX_FILE_PERMISSIONS);
fclose($fd);
return true;
}
function GetScriptFileExt()
{
static $FILEMAN_SCRIPT_EXT = false;
if ($FILEMAN_SCRIPT_EXT !== false)
{
return $FILEMAN_SCRIPT_EXT;
}
$script_files = COption::GetOptionString("fileman", "~script_files", "php,php3,php4,php5,php6,php7,php8,phtml,pl,asp,aspx,cgi,dll,exe,ico,shtm,shtml,fcg,fcgi,fpl,asmx,pht,py,psp,var");
$arScriptFiles = [];
foreach (explode(",", mb_strtolower($script_files)) as $ext)
{
if (($e = trim($ext)) != "")
{
$arScriptFiles[] = $e;
}
}
$FILEMAN_SCRIPT_EXT = $arScriptFiles;
return $arScriptFiles;
}
function TrimUnsafe($path)
{
return rtrim($path, "\0.\\/+ ");
}
function RemoveScriptExtension($check_name)
{
$arExt = GetScriptFileExt();
$name = GetFileName($check_name);
$arParts = explode(".", $name);
foreach ($arParts as $i => $part)
{
if ($i > 0 && in_array(mb_strtolower(TrimUnsafe($part)), $arExt))
{
unset($arParts[$i]);
}
}
$path = mb_substr(TrimUnsafe($check_name), 0, -mb_strlen($name));
return $path . implode(".", $arParts);
}
function HasScriptExtension($check_name)
{
$arExt = GetScriptFileExt();
$check_name = GetFileName($check_name);
$arParts = explode(".", $check_name);
foreach ($arParts as $i => $part)
{
if ($i > 0 && in_array(mb_strtolower(TrimUnsafe($part)), $arExt))
{
return true;
}
}
return false;
}
function GetFileExtension($path)
{
$path = GetFileName($path);
if ($path <> '')
{
$pos = bxstrrpos($path, '.');
if ($pos !== false)
{
return mb_substr($path, $pos + 1);
}
}
return '';
}
function GetFileNameWithoutExtension($path)
{
$path = GetFileName($path);
if ($path <> '')
{
$pos = bxstrrpos($path, '.');
if ($pos !== false)
{
$path = mb_substr($path, 0, $pos);
}
return trim($path, '.');
}
return '';
}
function GetFileName($path)
{
$path = TrimUnsafe($path);
$path = str_replace("\\", "/", $path);
$path = rtrim($path, "/");
$p = bxstrrpos($path, "/");
if ($p !== false)
{
return mb_substr($path, $p + 1);
}
return $path;
}
function IsFileUnsafe($name)
{
static $arFiles = false;
if ($arFiles === false)
{
$fileList = COption::GetOptionString("main", "~unsafe_files", ".htaccess,.htpasswd,web.config,global.asax");
$arFiles = explode(",", mb_strtolower($fileList));
}
$name = GetFileName($name);
return in_array(mb_strtolower(TrimUnsafe($name)), $arFiles);
}
function IsConfigFile(string $path): bool
{
$path = TrimUnsafe($path);
static $list = [
"/bitrix/.settings.php",
"/.access.php",
];
foreach ($list as $file)
{
if (str_ends_with($path, $file))
{
return true;
}
}
return false;
}
function GetFileType($path)
{
$extension = GetFileExtension(mb_strtolower($path));
switch ($extension)
{
case "jpg":
case "jpeg":
case "gif":
case "bmp":
case "png":
$type = "IMAGE";
break;
case "swf":
$type = "FLASH";
break;
case "html":
case "htm":
case "asp":
case "aspx":
case "phtml":
case "php":
case "php3":
case "php4":
case "php5":
case "php6":
case "shtml":
case "sql":
case "txt":
case "inc":
case "js":
case "vbs":
case "tpl":
case "css":
case "shtm":
$type = "SOURCE";
break;
default:
$type = "UNKNOWN";
}
return $type;
}
function GetDirectoryIndex($path, $strDirIndex = false)
{
return GetDirIndex($path, $strDirIndex);
}
function GetDirIndex($path, $strDirIndex = false)
{
$doc_root = ($_SERVER["DOCUMENT_ROOT"] <> '' ? $_SERVER["DOCUMENT_ROOT"] : $GLOBALS["DOCUMENT_ROOT"]);
$dir = GetDirPath($path);
$arrDirIndex = GetDirIndexArray($strDirIndex);
if (is_array($arrDirIndex) && !empty($arrDirIndex))
{
foreach ($arrDirIndex as $page_index)
{
if (file_exists($doc_root . $dir . $page_index))
{
return $page_index;
}
}
}
return "index.php";
}
function GetDirIndexArray($strDirIndex = false)
{
static $arDefault = ["index.php", "index.html", "index.htm", "index.phtml", "default.html", "index.php3"];
if ($strDirIndex === false && !defined("DIRECTORY_INDEX"))
{
return $arDefault;
}
if ($strDirIndex === false && defined("DIRECTORY_INDEX"))
{
$strDirIndex = DIRECTORY_INDEX;
}
$arrRes = [];
$arr = explode(" ", $strDirIndex);
foreach ($arr as $page_index)
{
$page_index = trim($page_index);
if ($page_index <> '')
{
$arrRes[] = $page_index;
}
}
return $arrRes;
}
function GetPagePath($page = false, $get_index_page = null)
{
if (null === $get_index_page)
{
if (defined('BX_DISABLE_INDEX_PAGE'))
{
$get_index_page = !BX_DISABLE_INDEX_PAGE;
}
else
{
$get_index_page = true;
}
}
if ($page === false && !empty($_SERVER["REQUEST_URI"]))
{
$page = $_SERVER["REQUEST_URI"];
}
if ($page === false)
{
$page = $_SERVER["SCRIPT_NAME"];
}
$sPath = $page;
static $terminate = ["?", "#"];
foreach ($terminate as $term)
{
if (($found = mb_strpos($sPath, $term)) !== false)
{
$sPath = mb_substr($sPath, 0, $found);
}
}
//nginx fix
$sPath = preg_replace("/%+[0-9a-f]{0,1}$/i", "", $sPath);
$sPath = urldecode($sPath);
if (mb_substr($sPath, -1, 1) == "/" && $get_index_page)
{
$sPath .= GetDirectoryIndex($sPath);
}
$sPath = Rel2Abs("/", $sPath);
static $aSearch = ["<", ">", "\"", "'", "%", "\r", "\n", "\t", "\\"];
static $aReplace = ["<", ">", """, "'", "%25", "%0d", "%0a", "%09", "%5C"];
$sPath = str_replace($aSearch, $aReplace, $sPath);
return $sPath;
}
function GetRequestUri()
{
$uriPath = "/" . ltrim($_SERVER["REQUEST_URI"] ?? '', "/");
if (($index = mb_strpos($uriPath, "?")) !== false)
{
$uriPath = mb_substr($uriPath, 0, $index);
}
if (defined("BX_DISABLE_INDEX_PAGE") && BX_DISABLE_INDEX_PAGE === true)
{
if (str_ends_with($uriPath, "/index.php"))
{
$uriPath = substr($uriPath, 0, -9);
}
}
$queryString = DeleteParam(["bxrand"]);
if ($queryString != "")
{
$uriPath = $uriPath . "?" . $queryString;
}
return $uriPath;
}
//light version of GetPagePath() for menu links
function GetFileFromURL($page, $get_index_page = null)
{
if (null === $get_index_page)
{
if (defined('BX_DISABLE_INDEX_PAGE'))
{
$get_index_page = !BX_DISABLE_INDEX_PAGE;
}
else
{
$get_index_page = true;
}
}
$found = mb_strpos($page, "?");
$sPath = ($found !== false ? mb_substr($page, 0, $found) : $page);
$sPath = urldecode($sPath);
if (mb_substr($sPath, -1, 1) == "/" && $get_index_page)
{
$sPath .= GetDirectoryIndex($sPath);
}
return $sPath;
}
function GetDirPath($sPath)
{
if ($sPath <> '')
{
$p = mb_strrpos($sPath, "/");
if ($p === false)
{
return '/';
}
else
{
return mb_substr($sPath, 0, $p + 1);
}
}
else
{
return '/';
}
}
/*
This function emulates php internal function basename
but does not behave badly on broken locale settings
*/
function bx_basename($path, $ext = "")
{
$path = rtrim($path, "\\/");
if (preg_match("#[^\\\\/]+$#", $path, $match))
{
$path = $match[0];
}
if ($ext)
{
$ext_len = mb_strlen($ext);
if (mb_strlen($path) > $ext_len && mb_substr($path, -$ext_len) == $ext)
{
$path = mb_substr($path, 0, -$ext_len);
}
}
return $path;
}
/**
* @deprecated Use \Bitrix\Main\Text\UtfSafeString::getLastPosition()
*/
function bxstrrpos($haystack, $needle)
{
return Text\UtfSafeString::getLastPosition($haystack, $needle);
}
function Rel2Abs($curdir, $relpath)
{
if ($relpath == "")
{
return false;
}
if (str_starts_with($relpath, "/") || preg_match("#^[a-z]:/#i", $relpath))
{
$res = $relpath;
}
else
{
if (!str_starts_with($curdir, "/") && !preg_match("#^[a-z]:/#i", $curdir))
{
$curdir = "/" . $curdir;
}
if (!str_ends_with($curdir, "/"))
{
$curdir .= "/";
}
$res = $curdir . $relpath;
}
if ((mb_strpos($res, "\0")) !== false)
{
throw new Main\IO\InvalidPathException($res);
}
$res = _normalizePath($res);
if (!str_starts_with($res, "/") && !preg_match("#^[a-z]:/#i", $res))
{
$res = "/" . $res;
}
$res = rtrim($res, ".\\+ ");
return $res;
}
/**
* @deprecated Use Main\IO\Path::normalize()
*/
function _normalizePath($strPath)
{
$strResult = '';
if ($strPath <> '')
{
if (strncasecmp(PHP_OS, "WIN", 3) == 0)
{
//slashes doesn't matter for Windows
$strPath = str_replace("\\", "/", $strPath);
}
$arPath = explode('/', $strPath);
$nPath = count($arPath);
$pathStack = [];
for ($i = 0; $i < $nPath; $i++)
{
if ($arPath[$i] === ".")
{
continue;
}
if (($arPath[$i] === '') && ($i !== ($nPath - 1)) && ($i !== 0))
{
continue;
}
if ($arPath[$i] === "..")
{
array_pop($pathStack);
}
else
{
array_push($pathStack, $arPath[$i]);
}
}
$strResult = implode("/", $pathStack);
}
return $strResult;
}
function removeDocRoot($path)
{
if (mb_substr($path, 0, mb_strlen($_SERVER["DOCUMENT_ROOT"])) == $_SERVER["DOCUMENT_ROOT"])
{
return "/" . ltrim(mb_substr($path, mb_strlen($_SERVER["DOCUMENT_ROOT"])), "/");
}
return $path;
}
function GetMessageJS($name, $aReplace = false)
{
return CUtil::JSEscape(GetMessage($name, $aReplace));
}
function GetMessage($name, $aReplace = null)
{
global $MESS;
if (isset($MESS[$name]))
{
$s = $MESS[$name];
if (is_array($aReplace))
{
$s = strtr($s, $aReplace);
}
return $s;
}
return Main\Localization\Loc::getMessage($name, $aReplace);
}
/**
* @deprecated
*/
function HasMessage($name)
{
global $MESS;
return isset($MESS[$name]);
}
global $ALL_LANG_FILES;
$ALL_LANG_FILES = [];
/** @deprecated */
function GetLangFileName($before, $after, $lang = false)
{
if ($lang === false)
{
$lang = LANGUAGE_ID;
}
global $ALL_LANG_FILES;
$ALL_LANG_FILES[] = $before . $lang . $after;
if (Main\Localization\Translation::allowConvertEncoding())
{
$langFile = Main\Localization\Translation::convertLangPath($before . $lang . $after, $lang);
if (file_exists($langFile))
{
return $langFile;
}
}
if (file_exists($before . $lang . $after))
{
return $before . $lang . $after;
}
if (file_exists($before . "en" . $after))
{
return $before . "en" . $after;
}
if (!str_contains($before, "/bitrix/modules/"))
{
return $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/lang/en/tools.php";
}
$old_path = rtrim($before, "/");
$old_path = mb_substr($old_path, mb_strlen($_SERVER["DOCUMENT_ROOT"]));
$path = mb_substr($old_path, 16);
$module = mb_substr($path, 0, mb_strpos($path, "/"));
$path = mb_substr($path, mb_strpos($path, "/"));
if (str_ends_with($path, "/lang"))
{
$path = substr($path, 0, -5);
}
IncludeModuleLangFile($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/" . $module . $path . $after, $lang);
return $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/" . $module . "/lang/" . $lang . $path . $after;
}
/**
* @deprecated Use Main\Localization\Loc
*/
function __IncludeLang($path, $bReturnArray = false, $bFileChecked = false)
{
global $ALL_LANG_FILES;
$ALL_LANG_FILES[] = $path;
if (Main\Localization\Translation::allowConvertEncoding())
{
// extract language from path
$language = '';
$arr = explode('/', $path);
$langKey = array_search('lang', $arr);
if ($langKey !== false && isset($arr[$langKey + 1]))
{
$language = $arr[$langKey + 1];
}
static $encodingCache = [];
if (isset($encodingCache[$language]))
{
[$convertEncoding, $targetEncoding, $sourceEncoding] = $encodingCache[$language];
}
else
{
$convertEncoding = Main\Localization\Translation::needConvertEncoding($language);
$targetEncoding = $sourceEncoding = '';
if ($convertEncoding)
{
$targetEncoding = Main\Localization\Translation::getCurrentEncoding();
$sourceEncoding = Main\Localization\Translation::getSourceEncoding($language);
}
$encodingCache[$language] = [$convertEncoding, $targetEncoding, $sourceEncoding];
}
$MESS = [];
if ($bFileChecked)
{
include($path);
}
else
{
$path = Main\Localization\Translation::convertLangPath($path, LANGUAGE_ID);
if (file_exists($path))
{
include($path);
}
}
if (!empty($MESS))
{
if ($convertEncoding)
{
$convertEncoding = Main\Localization\Translation::checkPathRestrictionConvertEncoding($path);
}
foreach ($MESS as $key => $val)
{
if ($convertEncoding)
{
if ($targetEncoding !== 'utf-8' || !preg_match('//u', $val))
{
$val = Main\Text\Encoding::convertEncoding($val, $sourceEncoding, $targetEncoding);
}
}
$MESS[$key] = $val;
if (!$bReturnArray)
{
$GLOBALS['MESS'][$key] = $val;
}
}
}
}
else
{
if ($bReturnArray)
{
$MESS = [];
}
else
{
global $MESS;
}
if ($bFileChecked)
{
include($path);
}
else
{
$path = Main\Localization\Translation::convertLangPath($path, LANGUAGE_ID);
if (file_exists($path))
{
include($path);
}
}
}
//read messages from user lang file
static $bFirstCall = true;
if ($bFirstCall)
{
$bFirstCall = false;
$fname = getLocalPath("php_interface/user_lang/" . LANGUAGE_ID . "/lang.php");
if ($fname !== false)
{
$arMess = __IncludeLang($_SERVER["DOCUMENT_ROOT"] . $fname, true, true);
foreach ($arMess as $key => $val)
{
$GLOBALS["MESS"][str_replace("\\", "/", realpath($_SERVER["DOCUMENT_ROOT"] . $key))] = $val;
}
}
}
//redefine messages from user lang file
$path = str_replace("\\", "/", realpath($path));
if (isset($GLOBALS["MESS"][$path]) && is_array($GLOBALS["MESS"][$path]))
{
foreach ($GLOBALS["MESS"][$path] as $key => $val)
{
$MESS[$key] = $val;
}
}
if ($bReturnArray)
{
return $MESS;
}
else
{
return true;
}
}
/**
* @deprecated Use Main\Localization\Loc
*/
function IncludeTemplateLangFile($filepath, $lang = false)
{
$filepath = rtrim(preg_replace("'[\\\\/]+'", "/", $filepath), "/ ");
$module_path = "/bitrix/modules/";
$module_name = $templ_path = $file_name = $template_name = "";
$dirs = [
"/local/templates/",
BX_PERSONAL_ROOT . "/templates/",
];
foreach ($dirs as $dir)
{
if (str_contains($filepath, $dir))
{
$templ_path = $dir;
$templ_pos = mb_strlen($filepath) - mb_strpos(strrev($filepath), strrev($templ_path));
$rel_path = mb_substr($filepath, $templ_pos);
$p = mb_strpos($rel_path, "/");
if (!$p)
{
return null;
}
$template_name = mb_substr($rel_path, 0, $p);
$file_name = mb_substr($rel_path, $p + 1);
$p = mb_strpos($file_name, "/");
if ($p > 0)
{
$module_name = mb_substr($file_name, 0, $p);
}
break;
}
}
if ($templ_path == "")
{
if (str_contains($filepath, $module_path))
{
$templ_pos = mb_strlen($filepath) - mb_strpos(strrev($filepath), strrev($module_path));
$rel_path = mb_substr($filepath, $templ_pos);
$p = mb_strpos($rel_path, "/");
if (!$p)
{
return null;
}
$module_name = mb_substr($rel_path, 0, $p);
if (defined("SITE_TEMPLATE_ID"))
{
$template_name = SITE_TEMPLATE_ID;
}
else
{
$template_name = ".default";
}
$file_name = mb_substr($rel_path, $p + mb_strlen("/install/templates/"));
}
else
{
return false;
}
}
$BX_DOC_ROOT = rtrim(preg_replace("'[\\\\/]+'", "/", $_SERVER["DOCUMENT_ROOT"]), "/ ");
$module_path = $BX_DOC_ROOT . $module_path;
if ($lang === false)
{
$lang = LANGUAGE_ID;
}
$subst_lang = LangSubst($lang);
if ((str_ends_with($file_name, ".description.php")) && $module_name != "")
{
if ($subst_lang <> $lang)
{
$fname = $module_path . $module_name . "/install/templates/lang/" . $subst_lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $subst_lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
}
}
$fname = $module_path . $module_name . "/install/templates/lang/" . $lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
}
}
$checkModule = true;
if ($templ_path <> "")
{
$templ_path = $BX_DOC_ROOT . $templ_path;
$checkDefault = true;
// default
if ($subst_lang <> $lang)
{
$fname = $templ_path . $template_name . "/lang/" . $subst_lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $subst_lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
$checkDefault = $checkModule = false;
}
}
// required lang
$fname = $templ_path . $template_name . "/lang/" . $lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
$checkDefault = $checkModule = false;
}
// template .default
if ($checkDefault && $template_name != ".default")
{
if ($subst_lang <> $lang)
{
$fname = $templ_path . ".default/lang/" . $subst_lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $subst_lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
$checkModule = false;
}
}
$fname = $templ_path . ".default/lang/" . $lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
$checkModule = false;
}
}
}
if ($checkModule && $module_name != "")
{
if ($subst_lang <> $lang)
{
$fname = $module_path . $module_name . "/install/templates/lang/" . $subst_lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $subst_lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
}
}
$fname = $module_path . $module_name . "/install/templates/lang/" . $lang . "/" . $file_name;
$fname = Main\Localization\Translation::convertLangPath($fname, $lang);
if (file_exists($fname))
{
__IncludeLang($fname, false, true);
}
}
return null;
}
function IncludeModuleLangFile($filepath, $lang = false, $bReturnArray = false)
{
if ($lang === false && $bReturnArray === false)
{
Main\Localization\Loc::loadMessages($filepath);
return true;
}
$filepath = rtrim(preg_replace("'[\\\\/]+'", "/", $filepath), "/ ");
$module_path = "/modules/";
if (str_contains($filepath, $module_path))
{
$pos = mb_strlen($filepath) - mb_strpos(strrev($filepath), strrev($module_path));
$rel_path = mb_substr($filepath, $pos);
$p = mb_strpos($rel_path, "/");
if (!$p)
{
return false;
}
$module_name = mb_substr($rel_path, 0, $p);
$rel_path = mb_substr($rel_path, $p + 1);
$BX_DOC_ROOT = rtrim(preg_replace("'[\\\\/]+'", "/", $_SERVER["DOCUMENT_ROOT"]), "/ ");
$module_path = $BX_DOC_ROOT . getLocalPath($module_path . $module_name);
}
elseif (str_contains($filepath, "/.last_version/"))
{
$pos = mb_strlen($filepath) - mb_strpos(strrev($filepath), strrev("/.last_version/"));
$rel_path = mb_substr($filepath, $pos);
$module_path = mb_substr($filepath, 0, $pos - 1);
}
else
{
return false;
}
if ($lang === false)
{
$lang = (defined('LANGUAGE_ID') ? LANGUAGE_ID : 'en');
}
$lang_subst = LangSubst($lang);
$arMess = [];
if ($lang_subst <> $lang)
{
$fname = $module_path . "/lang/" . $lang_subst . "/" . $rel_path;
$fname = Main\Localization\Translation::convertLangPath($fname, $lang_subst);
if (file_exists($fname))
{
$arMess = __IncludeLang($fname, $bReturnArray, true);
}
}
$fname = $module_path . "/lang/" . $lang . "/" . $rel_path;
$fname = Main\Localization\Translation::convertLangPath($fname, $lang);
if (file_exists($fname))
{
$msg = __IncludeLang($fname, $bReturnArray, true);
if (is_array($msg))
{
$arMess = array_merge($arMess, $msg);
}
}
if ($bReturnArray)
{
return $arMess;
}
return true;
}
/**
* @deprecated Use Main\Localization\Loc
*/
function LangSubst($lang)
{
return Main\Localization\Loc::getDefaultLang($lang);
}
function mydump($thing, $maxdepth = -1, $depth = 0)
{
$res = "";
$fmt = sprintf("%%%ds", 4 * $depth);
$pfx = sprintf($fmt, "");
$type = gettype($thing);
if ($type == 'array')
{
$n = sizeof($thing);
$res .= "$pfx array($n) => \n";
foreach (array_keys($thing) as $key)
{
$res .= " $pfx" . "[" . $key . "] =>\n";
$res .= mydump($thing[$key], $maxdepth, $depth + 1);
}
}
elseif ($type == 'string')
{
$n = mb_strlen($thing);
$res .= "$pfx string($n) =>\n";
$res .= "$pfx\"" . $thing . "\"\n";
}
elseif ($type == 'object')
{
$name = get_class($thing);
$res .= "$pfx object($name) =>\n";
$methodArray = get_class_methods($name);
foreach (array_keys($methodArray) as $m)
{
$res .= " $pfx method($m) => $methodArray" . "[" . $m . "]\n";
}
$classVars = get_class_vars($name);
foreach (array_keys($classVars) as $v)
{
$res .= " $pfx default => $v =>\n";
$res .= mydump($classVars[$v], $maxdepth, $depth + 2);
}
$objectVars = get_object_vars($thing);
foreach (array_keys($objectVars) as $v)
{
$res .= " $pfx $v =>\n";
$res .= mydump($objectVars[$v], $maxdepth, $depth + 2);
}
}
elseif ($type == 'boolean')
{
if ($thing)
{
$res .= "$pfx boolean(true)\n";
}
else
{
$res .= "$pfx boolean(false)\n";
}
}
else
{
$res .= "$pfx $type(" . $thing . ")\n";
}
return $res;
}
function SendError($error)
{
if (defined('ERROR_EMAIL') && ERROR_EMAIL <> '')
{
$from = (defined('ERROR_EMAIL_FROM') && ERROR_EMAIL_FROM <> '' ? ERROR_EMAIL_FROM : 'error@bitrix.ru');
$reply_to = (defined('ERROR_EMAIL_REPLY_TO') && ERROR_EMAIL_REPLY_TO <> '' ? ERROR_EMAIL_REPLY_TO : 'admin@bitrix.ru');
bxmail(ERROR_EMAIL, $_SERVER['HTTP_HOST'] . ": Error!",
$error .
"HTTP_GET_VARS:\n" . mydump($_GET) . "\n\n" .
"HTTP_POST_VARS:\n" . mydump($_POST) . "\n\n" .
"HTTP_COOKIE_VARS:\n" . mydump($_COOKIE) . "\n\n" .
"HTTP_SERVER_VARS:\n" . mydump($_SERVER) . "\n\n",
"From: " . $from . "\r\n" .
"Reply-To: " . $reply_to . "\r\n" .
"X-Mailer: PHP/" . phpversion()
);
}
}
function AddMessage2Log($text, $module = '', $traceDepth = 6, $showArgs = false)
{
if (defined('LOG_FILENAME') && LOG_FILENAME <> '')
{
$logger = Diag\Logger::create('main.Default', [LOG_FILENAME, $showArgs]);
if ($logger === null)
{
$logger = new Diag\FileLogger(LOG_FILENAME, 0);
$formatter = new Diag\LogFormatter($showArgs);
$logger->setFormatter($formatter);
}
$trace = '';
if ($traceDepth > 0)
{
$trace = Main\Diag\Helper::getBackTrace($traceDepth, ($showArgs ? null : DEBUG_BACKTRACE_IGNORE_ARGS));
}
$context = [
'module' => $module,
'message' => $text,
'trace' => $trace,
];
$message = "Host: {host}\n"
. "Date: {date}\n"
. ($module != '' ? "Module: {module}\n" : '')
. "{message}\n"
. "{trace}"
. "{delimiter}\n";
$logger->debug($message, $context);
}
}
function AddEventToStatFile($module, $action, $tag, $label, $action_type = '', $user_id = null)
{
global $USER;
static $search = ["\t", "\n", "\r"];
static $replace = " ";
if (defined('ANALYTICS_FILENAME') && is_writable(ANALYTICS_FILENAME))
{
if ($user_id === null && is_object($USER) && !defined("BX_CHECK_AGENT_START"))
{
$user_id = $USER->GetID();
}
$content =
'{date}'
. "\t" . '{host}'
. "\t" . str_replace($search, $replace, $module)
. "\t" . str_replace($search, $replace, $action)
. "\t" . str_replace($search, $replace, $tag)
. "\t" . str_replace($search, $replace, $label)
. "\t" . str_replace($search, $replace, $action_type)
. "\t" . intval($user_id)
. "\n";
$logger = new Diag\FileLogger(ANALYTICS_FILENAME, 0);
$logger->debug($content);
}
}
function LocalRedirect($url, $skip_security_check = false, $status = "302 Found")
{
$redirectResponse = Context::getCurrent()->getResponse()->redirectTo($url);
$redirectResponse
->setSkipSecurity($skip_security_check)
->setStatus($status)
;
Application::getInstance()->end(0, $redirectResponse);
}
function WriteFinalMessage($message = "")
{
echo $message;
exit;
}
function FindUserID($tag_name, $tag_value, $user_name = "", $form_name = "form1", $tag_size = "3", $tag_maxlength = "", $button_value = "...", $tag_class = "typeinput", $button_class = "tablebodybutton", $search_page = "/bitrix/admin/user_search.php")
{
/** @global CMain $APPLICATION */
global $APPLICATION;
$selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/bitrix/admin/");
$search_page = str_replace("/bitrix/admin/", $selfFolderUrl, $search_page);
$tag_name_x = preg_replace("/([^a-z0-9]|\\[|\\])/is", "x", $tag_name);
if ($APPLICATION->GetGroupRight("main") >= "R")
{
$strReturn = "
" . $user_name . "
";
}
else
{
$strReturn = "
$user_name
";
}
return $strReturn;
}
function GetWhoisLink($ip, $class = '')
{
$URL = COption::GetOptionString('main', 'whois_service_url', 'http://whois.domaintools.com/#IP#');
$URL = str_replace("#IP#", urlencode($ip), $URL);
return ' '' ? ' class="' . $class . '"' : '') . ' target="_blank" title="' . GetMessage("WHOIS_SERVICE") . '">' . htmlspecialcharsbx($ip) . '';
}
function IsIE()
{
global $HTTP_USER_AGENT;
if (
!str_contains($HTTP_USER_AGENT, "Opera")
&& preg_match('#(MSIE|Internet Explorer) ([0-9]+)\\.([0-9]+)#', $HTTP_USER_AGENT, $version)
)
{
if (intval($version[2]) > 0)
{
return doubleval($version[2] . "." . $version[3]);
}
else
{
return false;
}
}
else
{
return false;
}
}
function GetCountryByID($id, $lang = LANGUAGE_ID)
{
$msg = IncludeModuleLangFile(__FILE__, $lang, true);
return $msg["COUNTRY_" . $id] ?? '';
}
function GetCountryArray($lang = LANGUAGE_ID)
{
$arMsg = IncludeModuleLangFile(__FILE__, $lang, true);
$arr = [];
if (is_array($arMsg))
{
foreach ($arMsg as $id => $country)
{
if (str_starts_with($id, "COUNTRY_"))
{
$arr[intval(mb_substr($id, 8))] = $country;
}
}
}
asort($arr);
$arCountry = ["reference_id" => array_keys($arr), "reference" => array_values($arr)];
return $arCountry;
}
function GetCountries($lang = LANGUAGE_ID)
{
static $countries = null;
if (isset($countries[$lang]))
{
return $countries[$lang];
}
include __DIR__ . '/countries.php';
$msg = IncludeModuleLangFile(__FILE__, $lang, true);
$countries[$lang] = [];
/** @var array $arCounries */
foreach ($arCounries as $country => $countryId)
{
$countries[$lang][$country] = [
'ID' => $countryId,
'CODE' => $country,
'NAME' => $msg['COUNTRY_' . $countryId],
];
}
return $countries[$lang];
}
function GetCountryIdByCode($code)
{
$code = strtoupper($code);
$countries = GetCountries();
return $countries[$code]['ID'] ?? false;
}
function GetCountryCodeById($countryId)
{
$countryId = (int)$countryId;
static $countryCodes = null;
if ($countryCodes === null)
{
include __DIR__ . '/countries.php';
/** @var array $arCounries */
$countryCodes = array_flip($arCounries);
}
return $countryCodes[$countryId] ?? '';
}
function minimumPHPVersion($vercheck)
{
$minver = explode(".", $vercheck);
$curver = explode(".", phpversion());
if ((intval($curver[0]) < intval($minver[0])) || ((intval($curver[0]) == intval($minver[0])) && (intval($curver[1]) < intval($minver[1]))) || ((intval($curver[0]) == intval($minver[0])) && (intval($curver[1]) == intval($minver[1])) && (intval($curver[2]) < intval($minver[2]))))
{
return false;
}
else
{
return true;
}
}
function FormDecode()
{
$superglobals = [
'_GET' => 1, '_SESSION' => 1, '_POST' => 1, '_COOKIE' => 1, '_REQUEST' => 1, '_FILES' => 1, '_SERVER' => 1, 'GLOBALS' => 1, '_ENV' => 1,
'DBType' => 1, 'DBDebug' => 1, 'DBDebugToFile' => 1, 'DBHost' => 1, 'DBName' => 1, 'DBLogin' => 1, 'DBPassword' => 1,
'HTTP_ENV_VARS' => 1, 'HTTP_GET_VARS' => 1, 'HTTP_POST_VARS' => 1, 'HTTP_POST_FILES' => 1, 'HTTP_COOKIE_VARS' => 1, 'HTTP_SERVER_VARS' => 1,
'this' => 1,
];
foreach ($superglobals as $gl => $t)
{
unset($_REQUEST[$gl]);
unset($_GET[$gl]);
unset($_POST[$gl]);
unset($_COOKIE[$gl]);
}
$register_globals = ini_get_bool("register_globals");
if (!$register_globals)
{
$toGlobals = [];
foreach ($_ENV as $key => $val)
{
if (!isset($superglobals[$key]))
{
$toGlobals[$key] = $val;
}
}
foreach ($_GET as $key => $val)
{
if (!isset($superglobals[$key]))
{
$toGlobals[$key] = $val;
}
}
foreach ($_POST as $key => $val)
{
if (!isset($superglobals[$key]))
{
$toGlobals[$key] = $val;
}
}
foreach ($_COOKIE as $key => $val)
{
if (!isset($superglobals[$key]))
{
$toGlobals[$key] = $val;
}
}
foreach ($_SERVER as $key => $val)
{
if (!isset($superglobals[$key]))
{
$toGlobals[$key] = $val;
}
}
foreach ($toGlobals as $key => $val)
{
if (!isset($GLOBALS[$key]))
{
$GLOBALS[$key] = $val;
}
}
}
}
/**
* @deprecated Use Bitrix\Main\Web\HttpClient
*/
function QueryGetData($SITE, $PORT, $PATH, $QUERY_STR, &$errno, &$errstr, $sMethod = "GET", $sProto = "", $sContentType = 'N')
{
$ob = new CHTTP();
$ob->Query(
$sMethod,
$SITE,
$PORT,
$PATH . ($sMethod == 'GET' ? ((!str_contains($PATH, '?') ? '?' : '&') . $QUERY_STR) : ''),
$sMethod == 'POST' ? $QUERY_STR : false,
$sProto,
$sContentType
);
$errno = $ob->errno;
$errstr = $ob->errstr;
return $ob->result;
}
function xmlize_xmldata($data)
{
$data = trim($data);
$vals = $index = $array = [];
$parser = xml_parser_create("ISO-8859-1");
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $vals, $index);
xml_parser_free($parser);
$i = 0;
$tagname = $vals[$i]['tag'];
if (isset($vals[$i]['attributes']))
{
$array[$tagname]['@'] = $vals[$i]['attributes'];
}
else
{
$array[$tagname]['@'] = [];
}
$array[$tagname]["#"] = xml_depth_xmldata($vals, $i);
return $array;
}
function xml_depth_xmldata($vals, &$i)
{
$children = [];
if (isset($vals[$i]['value']))
{
array_push($children, $vals[$i]['value']);
}
while (++$i < count($vals))
{
switch ($vals[$i]['type'])
{
case 'open':
$tagname = $vals[$i]['tag'] ?? '';
if (isset($children[$tagname]))
{
$size = sizeof($children[$tagname]);
}
else
{
$size = 0;
}
if (isset($vals[$i]['attributes']))
{
$children[$tagname][$size]['@'] = $vals[$i]["attributes"];
}
$children[$tagname][$size]['#'] = xml_depth_xmldata($vals, $i);
break;
case 'cdata':
array_push($children, $vals[$i]['value']);
break;
case 'complete':
$tagname = $vals[$i]['tag'];
if (isset($children[$tagname]))
{
$size = sizeof($children[$tagname]);
}
else
{
$size = 0;
}
if (isset($vals[$i]['value']))
{
$children[$tagname][$size]["#"] = $vals[$i]['value'];
}
else
{
$children[$tagname][$size]["#"] = '';
}
if (isset($vals[$i]['attributes']))
{
$children[$tagname][$size]['@'] = $vals[$i]['attributes'];
}
break;
case 'close':
return $children;
}
}
return $children;
}
function Help($module = "", $anchor = "", $help_file = "")
{
/** @global CMain $APPLICATION */
global $APPLICATION, $IS_HELP;
if ($help_file == '')
{
$help_file = basename($APPLICATION->GetCurPage());
}
if ($anchor <> '')
{
$anchor = "#" . $anchor;
}
if ($IS_HELP !== true)
{
$height = "500";
//$width = "545";
$width = "780";
echo "";
$IS_HELP = true;
}
echo "
";
}
function InitBVar(&$var)
{
$var = ($var == "Y") ? "Y" : "N";
}
function init_get_params($url)
{
InitURLParam($url);
}
function InitURLParam($url = false)
{
if ($url === false)
{
$url = $_SERVER["REQUEST_URI"];
}
$start = mb_strpos($url, "?");
if ($start !== false)
{
$end = mb_strpos($url, "#");
$length = ($end > 0) ? $end - $start - 1 : mb_strlen($url);
$params = mb_substr($url, $start + 1, $length);
parse_str($params, $_GET);
parse_str($params, $arr);
$_REQUEST += $arr;
foreach ($arr as $key => $val)
{
if (!isset($GLOBALS[$key]))
{
$GLOBALS[$key] = $val;
}
}
}
}
function _ShowHtmlspec($str)
{
$str = str_replace(["
", "
", "
", "
"], "\n", $str);
$str = htmlspecialcharsbx($str, ENT_COMPAT, false);
$str = nl2br($str);
return $str;
}
function ShowNote($strNote, $cls = "notetext")
{
/** @global CMain $APPLICATION */
global $APPLICATION;
if ($strNote <> "")
{
$APPLICATION->IncludeComponent(
"bitrix:system.show_message",
".default",
[
"MESSAGE" => $strNote,
"STYLE" => $cls,
],
null,
[
"HIDE_ICONS" => "Y",
]
);
}
}
function ShowError($strError, $cls = "errortext")
{
/** @global CMain $APPLICATION */
global $APPLICATION;
if ($strError <> "")
{
$APPLICATION->IncludeComponent(
"bitrix:system.show_message",
".default",
[
"MESSAGE" => $strError,
"STYLE" => $cls,
],
null,
[
"HIDE_ICONS" => "Y",
]
);
}
}
function ShowMessage($arMess)
{
/** @global CMain $APPLICATION */
global $APPLICATION;
if (!is_array($arMess))
{
$arMess = ["MESSAGE" => $arMess, "TYPE" => "ERROR"];
}
if (!empty($arMess["MESSAGE"]))
{
$APPLICATION->IncludeComponent(
"bitrix:system.show_message",
".default",
[
"MESSAGE" => $arMess["MESSAGE"],
"STYLE" => ($arMess["TYPE"] == "OK" ? "notetext" : "errortext"),
],
null,
[
"HIDE_ICONS" => "Y",
]
);
}
}
function DeleteParam($ParamNames)
{
if (empty($_GET))
{
return '';
}
$aParams = $_GET;
foreach (array_keys($aParams) as $key)
{
foreach ($ParamNames as $param)
{
if (strcasecmp($param, $key) == 0)
{
unset($aParams[$key]);
break;
}
}
}
return http_build_query($aParams, "", "&");
}
function check_email($email, $strict = false, $domainCheck = false)
{
if (!$strict)
{
$email = trim($email);
if (preg_match("#.*?[<\\[\\(](.*?)[>\\]\\)].*#i", $email, $arr) && $arr[1] <> '')
{
$email = $arr[1];
}
}
//http://tools.ietf.org/html/rfc2821#section-4.5.3.1
//4.5.3.1. Size limits and minimums
if (mb_strlen($email) > 320)
{
return false;
}
//http://tools.ietf.org/html/rfc2822#section-3.2.4
//3.2.4. Atom
//added \p{L} for international symbols
static $atom = "\\p{L}=_0-9a-z+~'!\$&*^`|\\#%/?{}-";
static $domain = "\\p{L}a-z0-9-";
//"." can't be in the beginning or in the end of local-part
//dot-atom-text = 1*atext *("." 1*atext)
if (preg_match("#^[{$atom}]+(\\.[{$atom}]+)*@(([{$domain}]+\\.)+)([{$domain}]{2,20})$#ui", $email))
{
if ($domainCheck)
{
$email = Main\Mail\Mail::toPunycode($email);
$parts = explode('@', $email);
$host = $parts[1] . '.';
return (checkdnsrr($host, 'MX') || checkdnsrr($host, 'A'));
}
return true;
}
return false;
}
function initvar($varname, $value = '')
{
global $$varname;
if (!isset($$varname))
{
$$varname = $value;
}
}
function ClearVars($prefix = "str_")
{
$n = mb_strlen($prefix);
foreach ($GLOBALS as $key => $val)
{
if (strncmp($key, $prefix, $n) == 0)
{
unset($GLOBALS[$key]);
}
}
}
function roundEx($value, $prec = 0)
{
$eps = 1.00 / pow(10, $prec + 4);
return round(doubleval($value) + $eps, $prec);
}
function roundDB($value, $len = 18, $dec = 4)
{
if ($value >= 0)
{
$value = "0" . $value;
}
$value = roundEx(DoubleVal($value), $len);
$value = sprintf("%01." . $dec . "f", $value);
if ($len > 0 && mb_strlen($value) > $len - $dec)
{
$value = trim(mb_substr($value, 0, $len - $dec), ".");
}
return $value;
}
function bitrix_sessid()
{
$kernelSession = Application::getInstance()->getKernelSession();
if (!$kernelSession->has('fixed_session_id'))
{
bitrix_sessid_set();
}
return $kernelSession->get('fixed_session_id');
}
function bitrix_sessid_set($val = false)
{
if ($val === false)
{
$val = bitrix_sessid_val();
}
Application::getInstance()->getKernelSession()->set("fixed_session_id", $val);
}
function bitrix_sessid_val()
{
return md5(CMain::GetServerUniqID() . Application::getInstance()->getKernelSession()->getId());
}
function bitrix_sess_sign()
{
return md5("nobody" . CMain::GetServerUniqID() . "nowhere");
}
function check_bitrix_sessid($varname = 'sessid')
{
$request = Main\Context::getCurrent()->getRequest();
return (
$request[$varname] === bitrix_sessid() ||
$request->getHeader('X-Bitrix-Csrf-Token') === bitrix_sessid()
);
}
function bitrix_sessid_get($varname = 'sessid')
{
return $varname . "=" . bitrix_sessid();
}
function bitrix_sessid_post($varname = 'sessid', $returnInvocations = false)
{
static $invocations = 0;
if ($returnInvocations)
{
return $invocations;
}
$id = $invocations ? $varname . '_' . $invocations : $varname;
$invocations++;
return '';
}
function print_url($strUrl, $strText, $sParams = "")
{
return ($strUrl == '' ? $strText : "" . $strText . "");
}
function IncludeAJAX()
{
/** @global CMain $APPLICATION */
global $APPLICATION;
$APPLICATION->AddHeadString('', true);
$APPLICATION->AddHeadScript('/bitrix/js/main/cphttprequest.js', true);
}
function GetMenuTypes($site = false, $default_value = false)
{
if ($default_value === false)
{
$default_value = "left=" . GetMessage("main_tools_menu_left") . ",top=" . GetMessage("main_tools_menu_top");
}
$mt = COption::GetOptionString("fileman", "menutypes", $default_value, $site);
if (!$mt)
{
return [];
}
$armt_ = unserialize(stripslashes($mt), ['allowed_classes' => false]);
$armt = [];
if (is_array($armt_))
{
foreach ($armt_ as $key => $title)
{
$key = trim($key);
if ($key == '')
{
continue;
}
$armt[$key] = trim($title);
}
return $armt;
}
$armt_ = explode(",", $mt);
for ($i = 0, $c = count($armt_); $i < $c; $i++)
{
$pos = mb_strpos($armt_[$i], '=');
if ($pos === false)
{
continue;
}
$key = trim(mb_substr($armt_[$i], 0, $pos));
if ($key == '')
{
continue;
}
$armt[$key] = trim(mb_substr($armt_[$i], $pos + 1));
}
return $armt;
}
function SetMenuTypes($armt, $site = '', $description = false)
{
return COption::SetOptionString('fileman', "menutypes", addslashes(serialize($armt)), $description, $site);
}
function ParseFileContent($filesrc, $params = [])
{
/////////////////////////////////////
// Parse prolog, epilog, title
/////////////////////////////////////
$filesrc = trim($filesrc);
$prolog = $epilog = '';
$php_doubleq = false;
$php_singleq = false;
$php_comment = false;
$php_star_comment = false;
$php_line_comment = false;
if (!empty($params["use_php_parser"]) && str_starts_with($filesrc, ""))
{
$phpChunks = PHPParser::getPhpChunks($filesrc);
if (!empty($phpChunks))
{
$prolog = $phpChunks[0];
$filesrc = mb_substr($filesrc, mb_strlen($prolog));
}
}
elseif (str_starts_with($filesrc, ""))
{
$fl = mb_strlen($filesrc);
$p = 2;
while ($p < $fl)
{
$ch2 = mb_substr($filesrc, $p, 2);
$ch1 = mb_substr($ch2, 0, 1);
if ($ch2 == "?>" && !$php_doubleq && !$php_singleq && !$php_star_comment)
{
$p += 2;
break;
}
elseif (!$php_comment && $ch2 == "//" && !$php_doubleq && !$php_singleq)
{
$php_comment = $php_line_comment = true;
$p++;
}
elseif ($php_line_comment && ($ch1 == "\n" || $ch1 == "\r" || $ch2 == "?>"))
{
$php_comment = $php_line_comment = false;
}
elseif (!$php_comment && $ch2 == "/*" && !$php_doubleq && !$php_singleq)
{
$php_comment = $php_star_comment = true;
$p++;
}
elseif ($php_star_comment && $ch2 == "*/")
{
$php_comment = $php_star_comment = false;
$p++;
}
elseif (!$php_comment)
{
if (($php_doubleq || $php_singleq) && $ch2 == "\\\\")
{
$p++;
}
elseif (!$php_doubleq && $ch1 == '"')
{
$php_doubleq = true;
}
elseif ($php_doubleq && $ch1 == '"' && mb_substr($filesrc, $p - 1, 1) != '\\')
{
$php_doubleq = false;
}
elseif (!$php_doubleq)
{
if (!$php_singleq && $ch1 == "'")
{
$php_singleq = true;
}
elseif ($php_singleq && $ch1 == "'" && mb_substr($filesrc, $p - 1, 1) != '\\')
{
$php_singleq = false;
}
}
}
$p++;
}
$prolog = mb_substr($filesrc, 0, $p);
$filesrc = mb_substr($filesrc, $p);
}
elseif (preg_match("'(.*?.*?)(.*)$'is", $filesrc, $reg))
{
$prolog = $reg[1];
$filesrc = $reg[2];
}
$title = PHPParser::getPageTitle($filesrc, $prolog);
$arPageProps = [];
if ($prolog <> '')
{
if (preg_match_all("'\\\$APPLICATION->SetPageProperty\\(([\"\\'])(.*?)(? $m1)
{
$arPageProps[UnEscapePHPString($m1, $out[1][$i])] = UnEscapePHPString($out[4][$i], $out[3][$i]);
}
}
}
if (str_ends_with($filesrc, "?>"))
{
if (isset($phpChunks) && count($phpChunks) > 1)
{
$epilog = $phpChunks[count($phpChunks) - 1];
$filesrc = mb_substr($filesrc, 0, -mb_strlen($epilog));
}
else
{
$p = mb_strlen($filesrc) - 2;
while (($p > 0) && (mb_substr($filesrc, $p, 2) != ""))
{
$p--;
}
$epilog = mb_substr($filesrc, $p);
$filesrc = mb_substr($filesrc, 0, $p);
}
}
return [
"PROLOG" => $prolog,
"TITLE" => $title,
"PROPERTIES" => $arPageProps,
"CONTENT" => $filesrc,
"EPILOG" => $epilog,
];
}
function EscapePHPString($str, $encloser = '"')
{
if ($encloser == "'")
{
$from = ["\\", "'"];
$to = ["\\\\", "\\'"];
}
else
{
$from = ["\\", "\$", "\""];
$to = ["\\\\", "\\\$", "\\\""];
}
return str_replace($from, $to, $str);
}
function UnEscapePHPString($str, $encloser = '"')
{
if ($encloser == "'")
{
$from = ["\\\\", "\\'"];
$to = ["\\", "'"];
}
else
{
$from = ["\\\\", "\\\$", "\\\""];
$to = ["\\", "\$", "\""];
}
return str_replace($from, $to, $str);
}
function CheckSerializedData($str, $max_depth = 200)
{
if (preg_match('/(^|;)[OC]\\:\\+{0,1}\\d+:/', $str)) // serialized objects
{
return false;
}
return true;
}
function NormalizePhone($number, $minLength = 10)
{
$minLength = intval($minLength);
if ($minLength <= 0 || mb_strlen($number) < $minLength)
{
return false;
}
if (mb_strlen($number) >= 10 && str_starts_with($number, '+8'))
{
$number = '00' . mb_substr($number, 1);
}
$number = preg_replace("/[^0-9\#\*,;]/i", "", $number);
if (mb_strlen($number) >= 10)
{
if (str_starts_with($number, '80') || str_starts_with($number, '81') || str_starts_with($number, '82'))
{
}
elseif (str_starts_with($number, '00'))
{
$number = substr($number, 2);
}
elseif (str_starts_with($number, '011'))
{
$number = substr($number, 3);
}
elseif (str_starts_with($number, '8'))
{
$number = '7' . substr($number, 1);
}
elseif (str_starts_with($number, '0'))
{
$number = substr($number, 1);
}
}
return $number;
}
function bxmail($to, $subject, $message, $additional_headers = "", $additional_parameters = "", Main\Mail\Context $context = null)
{
if (empty($context))
{
$context = new Main\Mail\Context();
}
$event = new Main\Event(
'main',
'OnBeforePhpMail',
[
'arguments' => (object)[
'to' => &$to,
'subject' => &$subject,
'message' => &$message,
'additional_headers' => &$additional_headers,
'additional_parameters' => &$additional_parameters,
'context' => &$context,
],
]
);
$event->send();
$defaultMailConfiguration = Configuration::getValue("smtp");
$smtpEnabled =
is_array($defaultMailConfiguration)
&& isset($defaultMailConfiguration['enabled'])
&& $defaultMailConfiguration['enabled'] === true;
if (
$smtpEnabled
&& (
$context->getSmtp() !== null
|| (!empty($defaultMailConfiguration['host']) && !empty($defaultMailConfiguration['login']))
)
)
{
$mailer = Main\Mail\Smtp\Mailer::getInstance($context);
return $mailer->sendMailBySmtp($to, $subject, $message, $additional_headers, $additional_parameters);
}
//message must not contain any null bytes
$message = str_replace("\0", ' ', $message);
if (function_exists("custom_mail"))
{
return custom_mail($to, $subject, $message, $additional_headers, $additional_parameters, $context);
}
if ($additional_parameters != "")
{
return @mail($to, $subject, $message, $additional_headers, $additional_parameters);
}
return @mail($to, $subject, $message, $additional_headers);
}
/**
* @deprecated Use \Bitrix\Main\Application::resetAccelerator().
*/
function bx_accelerator_reset()
{
Application::resetAccelerator();
}
/**
* @deprecated Use Main\Config\Ini::getBool().
*/
function ini_get_bool($param)
{
return Main\Config\Ini::getBool((string)$param);
}
/**
* Sorting array by column.
* You can use short mode: Collection::sortByColumn($arr, 'value'); This is equal Collection::sortByColumn($arr, array('value' => SORT_ASC))
*
* Pay attention: if two members compare as equal, their relative order in the sorted array is undefined. The sorting is not stable.
*
* More example:
* Collection::sortByColumn($arr, array('value' => array(SORT_NUMERIC, SORT_ASC), 'attr' => SORT_DESC), array('attr' => 'strlen'), 'www');
*
* @param array $array
* @param string|array $columns
* @param string|array $callbacks
* @param bool $preserveKeys If false numeric keys will be re-indexed. If true - preserve.
* @param null $defaultValueIfNotSetValue If value not set - use $defaultValueIfNotSetValue (any cols)
*/
function sortByColumn(array &$array, $columns, $callbacks = '', $defaultValueIfNotSetValue = null, $preserveKeys = false)
{
Main\Type\Collection::sortByColumn($array, $columns, $callbacks, $defaultValueIfNotSetValue, $preserveKeys);
}
function getLocalPath($path, $baseFolder = "/bitrix")
{
$root = rtrim($_SERVER["DOCUMENT_ROOT"], "\\/");
static $hasLocalDir = null;
if ($hasLocalDir === null)
{
$hasLocalDir = is_dir($root . "/local");
}
if ($hasLocalDir && file_exists($root . "/local/" . $path))
{
return "/local/" . $path;
}
elseif (file_exists($root . $baseFolder . "/" . $path))
{
return $baseFolder . "/" . $path;
}
// cli repository mode
if (empty($_SERVER["DOCUMENT_ROOT"]) || defined('REPOSITORY_ROOT'))
{
$root = realpath(__DIR__ . '/../../');
$localPath = $root . '/' . $path;
if (file_exists($localPath))
{
return $localPath;
}
}
return false;
}
/**
* Set session expired, e.g. if you want to destroy session after this hit
* @param bool $pIsExpired
*/
function setSessionExpired($pIsExpired = true)
{
Application::getInstance()->getKernelSession()->set("IS_EXPIRED", $pIsExpired);
}
/**
* @return bool
*/
function isSessionExpired()
{
return Application::getInstance()->getKernelSession()->get("IS_EXPIRED") === true;
}
$SHOWIMAGEFIRST = false;
function ShowImage($PICTURE_ID, $iMaxW = 0, $iMaxH = 0, $sParams = false, $strImageUrl = "", $bPopup = false, $strPopupTitle = false, $iSizeWHTTP = 0, $iSizeHHTTP = 0)
{
return CFile::ShowImage($PICTURE_ID, $iMaxW, $iMaxH, $sParams, $strImageUrl, $bPopup, $strPopupTitle, $iSizeWHTTP, $iSizeHHTTP);
}
function BXClearCache($full = false, $initdir = '')
{
CPHPCache::ClearCache($full, $initdir);
}
function RegisterModule($id)
{
Main\ModuleManager::registerModule($id);
}
function UnRegisterModule($id)
{
Main\ModuleManager::unRegisterModule($id);
}
function AddEventHandler($FROM_MODULE_ID, $MESSAGE_ID, $CALLBACK, $SORT = 100, $FULL_PATH = false)
{
$eventManager = Main\EventManager::getInstance();
return $eventManager->addEventHandlerCompatible($FROM_MODULE_ID, $MESSAGE_ID, $CALLBACK, $FULL_PATH, $SORT);
}
function RemoveEventHandler($FROM_MODULE_ID, $MESSAGE_ID, $iEventHandlerKey)
{
$eventManager = Main\EventManager::getInstance();
return $eventManager->removeEventHandler($FROM_MODULE_ID, $MESSAGE_ID, $iEventHandlerKey);
}
function GetModuleEvents($MODULE_ID, $MESSAGE_ID, $bReturnArray = false)
{
$eventManager = Main\EventManager::getInstance();
$arrResult = $eventManager->findEventHandlers($MODULE_ID, $MESSAGE_ID);
foreach ($arrResult as $k => $event)
{
$arrResult[$k]['FROM_MODULE_ID'] = $MODULE_ID;
$arrResult[$k]['MESSAGE_ID'] = $MESSAGE_ID;
}
if ($bReturnArray)
{
return $arrResult;
}
else
{
$resRS = new CDBResult;
$resRS->InitFromArray($arrResult);
return $resRS;
}
}
/**
* @deprecated
*/
function ExecuteModuleEvent($arEvent)
{
$args = [];
for ($i = 1, $nArgs = func_num_args(); $i < $nArgs; $i++)
{
$args[] = func_get_arg($i);
}
return ExecuteModuleEventEx($arEvent, $args);
}
function ExecuteModuleEventEx($arEvent, $arParams = [])
{
$result = true;
if (
isset($arEvent["TO_MODULE_ID"])
&& $arEvent["TO_MODULE_ID"] <> ""
&& $arEvent["TO_MODULE_ID"] <> "main"
)
{
if (!CModule::IncludeModule($arEvent["TO_MODULE_ID"]))
{
return null;
}
}
elseif (
isset($arEvent["TO_PATH"])
&& $arEvent["TO_PATH"] <> ""
&& file_exists($_SERVER["DOCUMENT_ROOT"] . BX_ROOT . $arEvent["TO_PATH"])
)
{
$result = include_once($_SERVER["DOCUMENT_ROOT"] . BX_ROOT . $arEvent["TO_PATH"]);
}
elseif (
isset($arEvent["FULL_PATH"])
&& $arEvent["FULL_PATH"] <> ""
&& file_exists($arEvent["FULL_PATH"])
)
{
$result = include_once($arEvent["FULL_PATH"]);
}
if ((empty($arEvent["TO_CLASS"]) || empty($arEvent["TO_METHOD"])) && !isset($arEvent["CALLBACK"]))
{
return $result;
}
if (isset($arEvent["TO_METHOD_ARG"]) && is_array($arEvent["TO_METHOD_ARG"]) && !empty($arEvent["TO_METHOD_ARG"]))
{
$args = array_merge($arEvent["TO_METHOD_ARG"], $arParams);
}
else
{
$args = $arParams;
}
//TODO: Возможно заменить на EventManager::getInstance()->getLastEvent();
global $BX_MODULE_EVENT_LAST;
$BX_MODULE_EVENT_LAST = $arEvent;
if (isset($arEvent["CALLBACK"]))
{
$result = call_user_func_array($arEvent["CALLBACK"], $args);
}
else
{
//php bug: http://bugs.php.net/bug.php?id=47948
if (class_exists($arEvent["TO_CLASS"]) && is_callable([$arEvent["TO_CLASS"], $arEvent["TO_METHOD"]]))
{
$result = call_user_func_array([$arEvent["TO_CLASS"], $arEvent["TO_METHOD"]], $args);
}
else
{
$exception = new SystemException("Event handler error: could not invoke {$arEvent["TO_CLASS"]}::{$arEvent["TO_METHOD"]}. Class or method does not exist.");
$application = Application::getInstance();
$exceptionHandler = $application->getExceptionHandler();
$exceptionHandler->writeToLog($exception);
$result = null;
}
}
return $result;
}
function UnRegisterModuleDependences($FROM_MODULE_ID, $MESSAGE_ID, $TO_MODULE_ID, $TO_CLASS = "", $TO_METHOD = "", $TO_PATH = "", $TO_METHOD_ARG = [])
{
$eventManager = Main\EventManager::getInstance();
$eventManager->unRegisterEventHandler($FROM_MODULE_ID, $MESSAGE_ID, $TO_MODULE_ID, $TO_CLASS, $TO_METHOD, $TO_PATH, $TO_METHOD_ARG);
}
function RegisterModuleDependences($FROM_MODULE_ID, $MESSAGE_ID, $TO_MODULE_ID, $TO_CLASS = "", $TO_METHOD = "", $SORT = 100, $TO_PATH = "", $TO_METHOD_ARG = [])
{
$eventManager = Main\EventManager::getInstance();
$eventManager->registerEventHandlerCompatible($FROM_MODULE_ID, $MESSAGE_ID, $TO_MODULE_ID, $TO_CLASS, $TO_METHOD, $SORT, $TO_PATH, $TO_METHOD_ARG);
}
function IsModuleInstalled($module_id)
{
return Main\ModuleManager::isModuleInstalled($module_id);
}
function GetModuleID($str)
{
$arr = explode("/", $str);
$i = array_search("modules", $arr);
return $arr[$i + 1];
}
/**
* @deprecated Use version_compare()
* Returns TRUE if version1 >= version2
* version1 = "XX.XX.XX"
* version2 = "XX.XX.XX"
*/
function CheckVersion($version1, $version2)
{
return (version_compare($version1, $version2) >= 0);
}