change nginx.conf

This commit is contained in:
F4ilji
2026-01-22 13:38:34 +05:00
parent 8104d0b6cd
commit c4be035890
47 changed files with 8872 additions and 0 deletions
@@ -0,0 +1,8 @@
<?php
return array(
'no_use_template_for_routes' => array(
'/abitur/profile/index.html' => '/abitur/profile/index.html',
'/vsoko/survey/index.html' => '/vsoko/survey/index.html',
)
);
+86
View File
@@ -0,0 +1,86 @@
<?php
$selfDir = dirname(__FILE__);
ini_set('max_execution_time', '60');
ini_set('default_socket_timeout', '60');
$locationOfVikonModules = '/'; //todo new_core_after del
$domenName = 'www.ntspi.ru';
$apiDomen = 'https://db-nica.ru/';
$vikonDomainResolveBypass = 'db-nica.ru:443:62.76.112.192';
$fmDomainResolveBypass = 'file.db-nica.ru:443:62.76.112.192';
$apiDomainAuth = 'https://auth.db-nica.ru/';
$filemanagerApiDomen = 'https://file.db-nica.ru/';
$clientId = '542';
$clientSecret = '0mmk80mv8zpk7h5uhjvjsmsskvpkn9nmkywgy83vwg7tpzdw0y7rao0k9pvmn8xxwj5mgw8554nhtq6s';
$vuzId = '16775';
$vuzName = 'Нижнетагильский государственный социально-педагогический институт (филиал) "Российского государственного профессионально-педагогического университета"';
$modulesByPathDeploy = array (
2 => 'abitur',
1 => 'sveden',
6 => 'vsoko',
);
$allowedFoldersInCoreByModule = array (
2 =>
array (
0 => 'abitur',
),
1 =>
array (
0 => 'assets',
1 => 'files_zaglushka',
2 => 'common',
3 => 'struct',
4 => 'document',
5 => 'education',
6 => 'managers',
7 => 'employees',
8 => 'objects',
9 => 'paid_edu',
10 => 'budget',
11 => 'vacant',
12 => 'grants',
13 => 'inter',
14 => 'catering',
15 => 'eduStandarts',
16 => 'corruption',
17 => 'antiterrorism',
18 => 'files',
19 => 'update',
20 => 'index.html',
21 => '.vikon',
22 => '.htaccess',
),
6 =>
array (
0 => 'assets',
1 => 'general',
2 => 'structure',
4 => 'faq',
5 => 'procedures',
6 => 'results-and-reports',
7 => 'plans',
8 => 'survey',
9 => 'files',
10 => '.vikon',
11 => 'index.html',
12 => '.htaccess',
),
);
define('DEBUG_MODE', isset($_GET['debug_mode']) && $_GET['debug_mode'] || isset($_POST['debug_mode']) && $_POST['debug_mode']);
define('IS_DOMAIN_RESOLVE', isset($_COOKIE['is_resolve_domain']) ? (int) $_COOKIE['is_resolve_domain'] : 0);
define('FM_DOMAIN_RESOLVE_BYPASS', $fmDomainResolveBypass);
define('VIKON_DOMAIN_RESOLVE_BYPASS', $vikonDomainResolveBypass);
define('SVEDEN', 1);
define('ABITUR', 2);
define('VSOKO', 6);
if (DEBUG_MODE === true) {
error_reporting(E_ALL);
ini_set('display_errors','on');
} else {
error_reporting(0);
}
+353
View File
@@ -0,0 +1,353 @@
<?php
require_once 'path.php';
class Filesystem
{
public static function getExtension($path)
{
if ($path === '') {
return '';
}
$extension = pathinfo($path, PATHINFO_EXTENSION);
return strtolower($extension);
}
/**
* Выполняет безопасный scandir, убирает системные точки
*
* @param $path
* @return array|false - возращает entries внутри сканируемой папки или false, в случае отсутсвия прав (или других причин)
*/
public static function safeScandir($path)
{
if (!is_dir($path) || !is_readable($path)) {
return false;
}
$entries = scandir($path);
if ($entries === false) {
return false;
}
return array_diff($entries, Path::getSystemDots($path));
}
public static function removeZip($path, $withCheckRights)
{
if (!Path::isActionAllowedThisPath($path)) {
return false;
}
if (empty($path) || !file_exists($path)) {
return true;
}
if ($withCheckRights) {
$checks = array(
'is_file' => is_file($path),
'is_zip' => self::getExtension($path) === 'zip',
'is_writable' => is_writable($path)
);
foreach ($checks as $check) {
if (!$check) {
return false;
}
}
}
return unlink($path);
}
/**
* @param string $path
* @param bool $withRecursive
* @param int|null $moduleId - Важный параметр который дает понимание в рамках какой папки мы работаем
* Если null - работаем в рамках vikon_core, переданный moduleId - даст путь к модулю
* @return bool
*/
public static function remove($path, $withRecursive, $moduleId = null)
{
if (!Path::isActionAllowedThisPath($path, $moduleId)) {
return false;
}
if (!file_exists($path)) {
return true;
}
if (!is_dir($path)) {
return unlink($path);
}
if (!$withRecursive) {
return rmdir($path);
}
$success = true;
$entries = self::safeScandir($path);
foreach ($entries as $entry) {
$fullPath = Path::join($path, $entry);
if (is_dir($fullPath) && !is_link($fullPath)) {
if (!self::remove($fullPath, $withRecursive, $moduleId)) {
$success = false;
}
} else {
if (!unlink($fullPath)) {
$success = false;
}
}
}
if ($success) {
if (!rmdir($path)) {
$success = false;
}
}
return $success;
}
/**
* Переносит и переименовывает папку и все содержимое рекурсивно
* Перед использованием выполни Filesysyem::remove($targetDir)
*
* В случае с replaceWithRename перемещать мы можем в рамках vikon_core и в рамках модуля
*/
public static function replaceWithRename($sourceDir, $targetDir, $moduleId = null)
{
if ($moduleId === null) {
if (!Path::isBasePath(Path::getCoreRootPath(), $sourceDir)) {
return false;
}
if (!Path::isBasePath(Path::getCoreRootPath(), $targetDir)) {
return false;
}
} else {
if (
!Path::isBasePath(Path::getModuleRootPath($moduleId), $sourceDir)
&& !Path::isBasePath(Path::getCoreRootPath(), $sourceDir)
) {
return false;
}
if (
!Path::isBasePath(Path::getModuleRootPath($moduleId), $targetDir)
&& !Path::isBasePath(Path::getCoreRootPath(), $targetDir)
) {
return false;
}
}
if (!file_exists($sourceDir)) {
return false;
}
if (file_exists($targetDir)) {
return false;
}
$parentDir = dirname($targetDir);
if (!is_writable($parentDir)) {
return false;
}
if (!mkdir($targetDir, 0755, true)) {
return false;
}
$entries = self::safeScandir($sourceDir);
if (empty($entries)) {
return rmdir($sourceDir);
}
foreach ($entries as $entry) {
$item = Path::join($sourceDir, $entry);
$newPath = Path::join($targetDir, $entry);
if (is_dir($item)) {
if (!self::replaceWithRename($item, $newPath, $moduleId)) {
return false;
}
} else {
if (!rename($item, $newPath)) {
return false;
}
}
}
return rmdir($sourceDir);
}
public static function safeRenameFile($oldPath, $newPath, $moduleId = null)
{
if ($moduleId === null) {
if (!Path::isBasePath(Path::getCoreRootPath(), $oldPath)) {
return false;
}
if (!Path::isBasePath(Path::getCoreRootPath(), $newPath)) {
return false;
}
} else {
if (
!Path::isBasePath(Path::getModuleRootPath($moduleId), $oldPath)
&& !Path::isBasePath(Path::getCoreRootPath(), $oldPath)
) {
return false;
}
if (
!Path::isBasePath(Path::getModuleRootPath($moduleId), $newPath)
&& !Path::isBasePath(Path::getCoreRootPath(), $newPath)
) {
return false;
}
}
if (!file_exists($oldPath)) {
return false;
}
if (file_exists($newPath)) {
return false;
}
$newDir = dirname($newPath);
if (!file_exists($newDir)) {
return false;
}
if (!is_writable($newDir)) {
return false;
}
if (!is_writable($oldPath)) {
return false;
}
$result = rename($oldPath, $newPath);
if (!$result) {
return false;
}
return true;
}
/**
* @param string $restorePath - путь к ядру модуля которое мы будем восстанавливать
* @param array $allowedRestoreFolders - разрешенные к восстановлению папки,
* т.е папки которые прилетели из архива, будем работать только с ними
* @return bool
*/
public static function restoreUnitCoreAfterFail($restorePath, $allowedRestoreFolders, $moduleId = null)
{
if (!Path::isActionAllowedThisPath($restorePath, $moduleId)) {
return false;
}
if (!file_exists($restorePath)) {
return false;
}
$restoreEntries = self::safeScandir($restorePath);
if ($restoreEntries === false) {
return false;
}
foreach ($restoreEntries as $restoreEntry) {
$fullPathRestore = Path::join($restorePath, $restoreEntry);
$baseName = substr($restoreEntry, 0, -4);
if (
file_exists($fullPathRestore)
&& substr($restoreEntry, -4) === Path::$n_pstfx
&& in_array($baseName, $allowedRestoreFolders)
) {
self::remove($fullPathRestore, true, $moduleId);
}
if (
file_exists($fullPathRestore)
&& substr($restoreEntry, -4) === Path::$o_pstfx
&& in_array($baseName, $allowedRestoreFolders)
) {
$newPath = Path::join($restorePath, $baseName);
if (file_exists($newPath)) {
self::remove($newPath, true, $moduleId);
}
self::replaceWithRename($fullPathRestore, $newPath, $moduleId);
}
}
return true;
}
/**
* @param $pathClean - Путь к ядру модуля или главному ядру, чтобы почистить его
* @param $excludedEntries - папки и файлы которые не нужно чистить в ядре
* @param int|null $moduleId - модуль id или false - когда проверяем ядро
* @return bool|string
*/
public static function cleanUnitCore($pathClean, $excludedEntries, $moduleId = null)
{
if (!Path::isActionAllowedThisPath($pathClean, $moduleId)) {
return false;
}
$entries = self::safeScandir($pathClean);
foreach ($entries as $entry) {
$item = Path::join($pathClean, $entry);
if (in_array($entry, $excludedEntries)) {
continue;
}
if (is_dir($item) && !is_link($item)) {
if (!self::remove($item, true, $moduleId)) {
return $item;
}
} else {
if (!unlink($item)) {
return $item;
}
}
}
return true;
}
public static function safeMkdir($path, $mode, $moduleId = null)
{
if (!Path::isActionAllowedThisPath($path, $moduleId)) {
return false;
}
if (file_exists($path)) {
return true;
}
$parentDir = dirname($path);
if (!is_dir($parentDir)) {
return false;
}
if (!is_writable($parentDir)) {
return false;
}
return mkdir($path, $mode);
}
public static function safeMkfile($filename, $mode, $content = '')
{
if (file_exists($filename)) {
return true;
}
$directory = dirname($filename);
if (!is_writable($directory)) {
return false;
}
if (file_put_contents($filename, $content) === false) {
return false;
}
if (!chmod($filename, $mode)) {
return false;
}
return true;
}
public static function ensureValidDirectoryAndFileName($directory, $filename)
{
if ($directory !== null && (!is_string($directory) || !preg_match("/^[a-z]{3,4}$/", $directory))) {
return false;
}
if (!is_string($filename) || strpos($filename, '/') !== false || strpos($filename, "\\") !== false) {
return false;
}
return true;
}
}
+238
View File
@@ -0,0 +1,238 @@
<?php
function loadHeaders()
{
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
}
function sendErrorResponse($code, $message)
{
$resultBody = array(
'success' => false,
'forward_code' => $code,
'message' => $message,
);
loadHeaders();
setResponseCode(200);
echo json_encode($resultBody);
die();
}
function sendSuccessResponse($message)
{
$resultBody = array(
'success' => true,
'forward_code' => 200,
'message' => $message,
);
loadHeaders();
setResponseCode(200);
echo json_encode($resultBody);
die();
}
// unpackZip плохо проверяет может ли он распаковать в этой папке
// перед использованием сделай Filesystem::remove($pathToUnpack) - чтобы убедиться что проблем не будет
function unpackZip($fileName, $pathToUnpack)
{
$res = array();
$res['success'] = false;
$res['message'] = '';
if($pathToUnpack) {
if (extension_loaded('zip')) {
$zip = new ZipArchive;
if ($isOpenedZip = $zip->open($fileName)) {
$zip->extractTo($pathToUnpack);
$zip->close();
$res['success'] = true;
} else {
$res['message'] = 'Ошибка при распоковке файлов библиотеки ZIP:' . $isOpenedZip;
}
} else {
require_once dirname(__FILE__) . '/../update/zip_helper.php';
$archive = new PclZip($fileName);
$unZipResult = $archive->extract(PCLZIP_OPT_PATH, $pathToUnpack,
PCLZIP_CB_PRE_EXTRACT, 'preExtractCallback', PCLZIP_OPT_REPLACE_NEWER);
if ($unZipResult == 0) {
$res['message'] = 'Ошибка при распоковке файлов:' . $archive->errorInfo(true);
} else {
$res['success'] = true;
}
$archive->privCloseFd();
}
}
return $res;
}
function filterAccessToken($token)
{
return filter_var($token, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[a-z0-9_\-\.]+$/i')));
}
function filterFileName($file)
{
return filter_var($file, FILTER_VALIDATE_REGEXP,
array('options' => array('regexp' => '/^[a-z0-9\+\.\,\(\)\;\#\№\-\_\«\»\!\%\=\$\@\'\&\–]+$/i'))
);
}
function filterPath($file)
{
return filter_var($file, FILTER_VALIDATE_REGEXP,
array('options' => array('regexp' => '/^[a-z0-9\.\-\_\–\/]+$/i'))
);
}
function filterEntry($entry)
{
return filter_var($entry, FILTER_VALIDATE_REGEXP,
array('options' => array('regexp' => '/^\/(?:[a-zA-Zа-яА-Я0-9_\-\.]+(?:\/)?)+$/'))
);
}
function filterInt($number)
{
return filter_var($number, FILTER_VALIDATE_INT);
}
function filterUrl($url)
{
return filter_var($url, FILTER_VALIDATE_URL);
}
function filterVersion($version)
{
return filter_var($version, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[0-9\.]+$/')));
}
function filterPartName($part)
{
return filter_var($part, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[a-z_\-]+$/i')));
}
function filterLogin($str)
{
return filter_var($str, FILTER_VALIDATE_EMAIL);
}
function filterPassword($str)
{
return filter_var($str, FILTER_SANITIZE_STRING);
}
function setResponseCode($code, $reason = null) {
$code = intval($code);
if (version_compare(phpversion(), '5.4', '>') && is_null($reason)) {
http_response_code($code);
} else {
header(trim("HTTP/1.0 $code $reason"));
}
}
function preExtractCallback($preEvent, &$preHeader)
{
if (!is_dir($preHeader['filename'])) {
if (strpos($preHeader['filename'], '.htaccess')) {
return 0;
}
if (file_exists($preHeader['filename'])) {
unlink($preHeader['filename']);
}
}
return 1;
}
class RemoteResult
{
public $curlHasError = true;
public $curlErrorTxt = '';
public $code = 0;
public $responseBody = '';
}
function remoteRequest($url, $responseAsJson = true, $postFields = false, $headers = array())
{
$result = new RemoteResult();
$ch = curl_init();
if (IS_DOMAIN_RESOLVE === 1) {
curl_setopt($ch, CURLOPT_RESOLVE, array(
VIKON_DOMAIN_RESOLVE_BYPASS,
FM_DOMAIN_RESOLVE_BYPASS,
));
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if (is_array($postFields)) {
curl_setopt($ch, CURLOPT_POST, true);
$postVars = "";
foreach ($postFields as $key => $value) {
$postVars .= $key . '=' . $value . '&';
}
$postVars = rtrim($postVars, '&');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postVars);
}
if ($headers !== array()) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$output = curl_exec($ch);
if (curl_errno($ch) > 0 || curl_error($ch)) {
$result->curlErrorTxt .= ';' . '#:' . curl_errno($ch) . 'Error:' . curl_error($ch);
} else{
$result->curlHasError = false;
$curlInfo = curl_getinfo($ch);
$result->code = (int) $curlInfo['http_code'];
$result->responseBody = ($responseAsJson) ? json_decode($output) : $output;
}
curl_close($ch);
return $result;
}
function tryExtractFmErrorMessage($remoteResultFmWhereBodyIsJson, $prefix = '')
{
$out = '';
if (property_exists($remoteResultFmWhereBodyIsJson->responseBody, 'error')) {
$out = $out . $remoteResultFmWhereBodyIsJson->responseBody->error;
}
if (
property_exists($remoteResultFmWhereBodyIsJson->responseBody, 'messages')
&& is_array($remoteResultFmWhereBodyIsJson->responseBody->messages)
) {
$message = version_compare(phpversion(), '8.0', '>=')
? implode('; ', $remoteResultFmWhereBodyIsJson->responseBody->messages)
: implode($remoteResultFmWhereBodyIsJson->responseBody->messages, '; ');
$out = $out . $message;
}
if ($out) {
$out = $prefix . 'Файловый сервер: ' . $out;
}
return $out;
}
function moduleDirIsEmptyOrEx($moduleRootPath, $flagFileOfModulePath)
{
if (is_dir($moduleRootPath)) {
if (count(Filesystem::safeScandir($moduleRootPath)) && !file_exists($flagFileOfModulePath)) {
throw new Exception(
'Ошибка при распаковке ядра модуля. Целевая директория: ' . $moduleRootPath . ' уже содержит данные. ' .
'Для запуска обновления целевая директория должна быть пуста. ' .
'Удалите или переместите существующие данные и повторите обновление.'
);
}
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
class Path
{
public static $vikonCoreFolder = 'vikon_core';
public static $functionalFolder = 'update';
public static $srcExecutor = 'src_executor.php';
public static $executorFile = 'executor.php';
private static $foldersCore = array();
private static $systemDots = array('.', '..');
public static $n_pstfx = '_new';
public static $o_pstfx = '_old';
/**
* Инициализация статических путей
* @param array $foldersCore
*/
public static function init($foldersCore)
{
self::$foldersCore = $foldersCore;
}
/**
* @param $path - Путь относительно которого необходимо вернуть систмные точки (., ..)
* @return array
*/
public static function getSystemDots($path)
{
$systemDots = array();
foreach (self::$systemDots as $systemDot) {
$systemDots[] = $systemDot;
$systemDots[] = $path.'/'.$systemDot;
}
return $systemDots;
}
/**
* Возвращает абсолютный путь к главному ядру
*
* @return string
*/
public static function getCoreRootPath()
{
return self::join(self::normalize(dirname(dirname(dirname(__FILE__)))), self::$vikonCoreFolder);
}
/**
* Возращает путь к функциональной папке главного ядра.
* Функциональная папка - папка в рамках которой проихсодит синхронизация и обновление частей и ядер
* vikon_core/update
*
* @return string
*/
public static function getFunctionalPath()
{
return self::join(self::getCoreRootPath(), self::$functionalFolder);
}
/**
* Возвращает абсолютный путь к папке модуля по его идентификатору
*
* @param string $moduleId
* @return string
*/
public static function getModuleRootPath($moduleId)
{
$parentFolderCore = self::normalize(dirname(self::getCoreRootPath()));
return self::join($parentFolderCore, self::$foldersCore[$moduleId]);
}
/**
* Возвращает абсолютный путь к папке версий
* @return string
*/
public static function getTmpVersionPath()
{
return self::join(self::getCoreRootPath(), 'tmp', 'versions');
}
/**
* @param int $moduleId Идентификатор модуля (1, 2 или 6).
* @return string|null Возвращает путь к директории модуля или null, если модуль не найден.
*/
public static function getFsPathByModule($moduleId)
{
return self::join(self::getModuleRootPath($moduleId), 'files');
}
/**
* Возращает путь к исходному коду для синхронизации ядра
*
* @return string
*/
public static function getSrcForExecutorPath()
{
return self::join(self::getFunctionalPath(), self::$srcExecutor);
}
/**
* Возвращает, является ли путь базовым для другого пути.
*/
public static function isBasePath($basePath, $ofPath)
{
$basePath = self::canonicalize($basePath);
$ofPath = self::canonicalize($ofPath);
$basePath = rtrim($basePath, '/').'/';
$ofPath = $ofPath.'/';
return 0 === strpos($ofPath, $basePath);
}
/**
* Объединяет несколько частей пути в один канонический путь
*
* @return string
*/
public static function join()
{
$paths = func_get_args();
$finalPath = null;
$wasScheme = false;
foreach ($paths as $path) {
if ('' === $path) {
continue;
}
if (null === $finalPath) {
$finalPath = $path;
$wasScheme = (strpos($path, '://') !== false);
continue;
}
$lastChar = substr($finalPath, -1);
if ('/' !== $lastChar && '\\' !== $lastChar) {
$finalPath .= '/';
}
if ($wasScheme) {
$finalPath .= $path;
} else {
$finalPath .= ltrim($path, '/');
}
$wasScheme = false;
}
if ($finalPath === null) {
return '';
}
return self::canonicalize($finalPath);
}
/**
* Преобразует путь в канонический вид (убирает '.', '..', двойные слеши)
*
* @param string $path
* @return string
*/
private static function canonicalize($path)
{
$path = self::normalize($path);
$parts = explode('/', $path);
$absolutes = array();
foreach ($parts as $part) {
if ('' === $part || '.' === $part) {
continue;
}
if ('..' === $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
$normalized = implode('/', $absolutes);
if ('/' === substr($path, 0, 1)) {
$normalized = '/' . $normalized;
}
return $normalized;
}
/**
* Проверяет возможность дальнейшей работы с заданным путем, дальнейшие действия должны проходить в рамках
* базовых путей vikon_core, или путей к модулю ($moduleId)
*
* @param int|null $moduleId - null - vikon_core, или id модуля
*/
public static function isActionAllowedThisPath($path, $moduleId = null)
{
if ($moduleId === null && !Path::isBasePath(Path::getCoreRootPath(), $path)) {
return false;
}
if ($moduleId && !Path::isBasePath(Path::getModuleRootPath($moduleId), $path)) {
return false;
}
return true;
}
/**
* Нормализует слеши в пути
*
* @param string $path
* @return string
*/
public static function normalize($path)
{
return str_replace('\\', '/', $path);
}
}