1
0

common.php 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847
  1. <?php
  2. if (!defined("CONFIG")) {
  3. die("Not defined");
  4. }
  5. require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/consts.php");
  6. require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/snmp.php");
  7. //ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
  8. //ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
  9. //$ValidMacAddressRegex="^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}|([0-9a-fA-F]{4}[\\.-][0-9a-fA-F]{4}[\\.-][0-9a-fA-F]{4})|[0-9A-Fa-f]{12}$";
  10. $config["init"] = 0;
  11. // #### vendor id
  12. // 1, Unknown
  13. // 2, 'Eltex'
  14. // 3, 'Huawei'
  15. // 4, 'Zyxel'
  16. // 5, 'Raisecom'
  17. // 6, 'SNR'
  18. // 7, 'Dlink'
  19. // 8, 'Allied Telesis'
  20. // 9, 'Mikrotik'
  21. // 10, 'NetGear'
  22. // 11, 'Ubiquiti'
  23. // 15, 'HP'
  24. // 16, 'Cisco'
  25. // 17, 'Maipu'
  26. // 18, 'Asus'
  27. // Функция для безопасного получения параметров
  28. /*
  29. FILTER_DEFAULT // Без фильтрации (по умолчанию)
  30. FILTER_UNSAFE_RAW // Без фильтрации (аналогично FILTER_DEFAULT)
  31. FILTER_CALLBACK // Пользовательская функция обратного вызова
  32. FILTER_VALIDATE_BOOLEAN // true/false/1/0/"1"/"0"/"yes"/"no"
  33. FILTER_VALIDATE_EMAIL // Email адрес
  34. FILTER_VALIDATE_FLOAT // Число с плавающей точкой
  35. FILTER_VALIDATE_INT // Целое число
  36. FILTER_VALIDATE_IP // IP адрес (IPv4/IPv6)
  37. FILTER_VALIDATE_REGEXP // По регулярному выражению
  38. FILTER_VALIDATE_URL // URL адрес
  39. FILTER_VALIDATE_DOMAIN // Доменное имя (PHP 7.0+)
  40. FILTER_SANITIZE_EMAIL // Удаляет все кроме букв, цифр и !#$%&'*+-/=?^_`{|}~@.[]
  41. FILTER_SANITIZE_ENCODED // URL-encode строка
  42. FILTER_SANITIZE_MAGIC_QUOTES // Apply addslashes()
  43. FILTER_SANITIZE_NUMBER_FLOAT // Удаляет все кроме цифр, +- и .,eE
  44. FILTER_SANITIZE_NUMBER_INT // Удаляет все кроме цифр и +-
  45. FILTER_SANITIZE_SPECIAL_CHARS // HTML-escape '"<>& и символы с ASCII < 32
  46. FILTER_SANITIZE_FULL_SPECIAL_CHARS // Эквивалентно htmlspecialchars()
  47. FILTER_SANITIZE_STRING // Устарело - используйте FILTER_SANITIZE_FULL_SPECIAL_CHARS
  48. FILTER_SANITIZE_STRIPPED // Устарело
  49. FILTER_SANITIZE_URL // Удаляет все кроме букв, цифр и $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=
  50. Flags::
  51. // Для FILTER_VALIDATE_BOOLEAN
  52. FILTER_NULL_ON_FAILURE // Возвращает null вместо false при failure
  53. // Для FILTER_VALIDATE_INT
  54. FILTER_FLAG_ALLOW_OCTAL // Разрешает восьмеричные числа (0123)
  55. FILTER_FLAG_ALLOW_HEX // Разрешает шестнадцатеричные числа (0x1A)
  56. // Для FILTER_VALIDATE_FLOAT
  57. FILTER_FLAG_ALLOW_THOUSAND // Разрешает разделитель тысяч (1,234.56)
  58. FILTER_FLAG_ALLOW_SCIENTIFIC// Разрешает научную нотацию (1.2e3)
  59. // Для FILTER_VALIDATE_IP
  60. FILTER_FLAG_IPV4 // Только IPv4
  61. FILTER_FLAG_IPV6 // Только IPv6
  62. FILTER_FLAG_NO_PRIV_RANGE // Запрещает частные IP (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
  63. FILTER_FLAG_NO_RES_RANGE // Запрещает зарезервированные IP
  64. FILTER_FLAG_GLOBAL_RANGE // Разрешает только глобальные IP
  65. // Для FILTER_VALIDATE_URL
  66. FILTER_FLAG_PATH_REQUIRED // Требует наличие path (/page.html)
  67. FILTER_FLAG_QUERY_REQUIRED // Требует наличие query string (?id=1)
  68. // Для FILTER_SANITIZE_STRING
  69. FILTER_FLAG_NO_ENCODE_QUOTES // Не кодировать кавычки
  70. FILTER_FLAG_STRIP_LOW // Удаляет символы с ASCII < 32
  71. FILTER_FLAG_STRIP_HIGH // Удаляет символы с ASCII > 127
  72. FILTER_FLAG_ENCODE_LOW // Кодирует символы с ASCII < 32
  73. FILTER_FLAG_ENCODE_HIGH // Кодирует символы с ASCII > 127
  74. FILTER_FLAG_ENCODE_AMP // Кодирует амперсанд (&)
  75. */
  76. function getParam($name, $page_url, $default = null, $filter = FILTER_DEFAULT, $options = []) {
  77. $value = filter_input(INPUT_POST, $name, $filter, $options) ?? filter_input(INPUT_GET, $name, $filter, $options);
  78. return $value !== null ? $value : ($_SESSION[$page_url][$name] ?? $default);
  79. }
  80. function getPOST($name, $page_url, $default = null, $filter = FILTER_DEFAULT, $options = []) {
  81. $value = filter_input(INPUT_POST, $name, $filter, $options);
  82. return $value !== null ? $value : ($_SESSION[$page_url][$name] ?? $default);
  83. }
  84. function intval_or_zero($v): int {
  85. return is_numeric($v) ? intval($v) : 0;
  86. }
  87. function normalize_vlan($vlan): int {
  88. $v = intval_or_zero($vlan);
  89. return ($v >= 1 && $v <= 4096) ? $v : 1;
  90. }
  91. function validate_dhcp_range(int $start, int $stop, int $net_start, int $net_stop): bool {
  92. if (!$start || !$stop) return false;
  93. if ($start >= $stop) return false;
  94. if ($start <= $net_start) return false;
  95. if ($stop >= $net_stop) return false;
  96. return true;
  97. }
  98. function get_dhcp_gateway($gw_raw, $fallback): int {
  99. $gw = ip2long(trim((string)$gw_raw));
  100. return $gw ? $gw : $fallback;
  101. }
  102. function safeUrlEncode($url) {
  103. // Сначала декодируем на случай двойного кодирования
  104. $decoded = urldecode($url);
  105. // Если после декодирования получили другой результат - значит был закодирован
  106. if ($decoded !== $url) {
  107. // Уже был закодирован - возвращаем декодированную версию
  108. return $url; // Или $decoded в зависимости от логики
  109. }
  110. // Не был закодирован - кодируем
  111. return urlencode($url);
  112. }
  113. function getSafeRedirectUrl(string $default = '/'): string {
  114. $url = filter_input(INPUT_GET, 'redirect_url', FILTER_SANITIZE_URL)
  115. ?? filter_input(INPUT_POST, 'redirect_url', FILTER_SANITIZE_URL)
  116. ?? $default;
  117. $default = safeUrlEncode($default);
  118. $decodedUrl = urldecode($url);
  119. // Проверяем:
  120. // 1. URL начинается с `/` (но не `//` или `http://`)
  121. // 2. Содержит только разрешённые символы (a-z, 0-9, -, _, /, ?, =, &, ., ~)
  122. if (!preg_match('/^\/(?!\/)[a-z0-9\-_\/?=&.~]*$/i', $decodedUrl)) {
  123. return $default;
  124. }
  125. // Проверяем:
  126. // 1. Начинается с /, не содержит //, ~, %00
  127. // 2. Разрешённые символы: a-z, 0-9, -, _, /, ?, =, &, .
  128. // 3. Допустимые форматы:
  129. // - /path/ (слэш на конце)
  130. // - /path (без слэша)
  131. // - /file.html (только .html)
  132. // - /script.php (только .php)
  133. // - Любой вариант с параметрами (?id=1)
  134. if (!preg_match(
  135. '/^\/' // Начинается с /
  136. . '(?!\/)' // Не //
  137. . '[a-z0-9\-_\/?=&.]*' // Разрешённые символы
  138. . '(?:\/' // Варианты окончаний:
  139. . '|\.(html|php)(?:\?[a-z0-9\-_=&]*)?' // .html/.php (+ параметры)
  140. . '|(?:\?[a-z0-9\-_=&]*)?' // Или параметры без расширения
  141. . ')$/i',
  142. $decodedUrl
  143. )) {
  144. return $default;
  145. }
  146. // Дополнительная защита: явно блокируем /config/, /vendor/ и т.д.
  147. if (preg_match('/(^|\/)(cfg|inc|log|sessions|tmp)(\/|$)/i', $decodedUrl)) {
  148. return $default;
  149. }
  150. return safeUrlEncode($url);
  151. }
  152. function randomPassword($length = 8)
  153. {
  154. $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  155. $pass = array(); //remember to declare $pass as an array
  156. $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
  157. for ($i = 0; $i < $length; $i++) {
  158. $n = rand(0, $alphaLength);
  159. $pass[] = $alphabet[$n];
  160. }
  161. return implode($pass); //turn the array into a string
  162. }
  163. if (!function_exists('mb_ucfirst')) {
  164. function mb_ucfirst(string $string, ?string $encoding = null): string
  165. {
  166. if ($string === '') {
  167. return '';
  168. }
  169. $encoding ??= mb_internal_encoding();
  170. $firstChar = mb_substr($string, 0, 1, $encoding);
  171. return mb_strtoupper($firstChar, $encoding) .
  172. mb_substr($string, 1, null, $encoding);
  173. }
  174. }
  175. function get_user_ip()
  176. {
  177. $auth_ip = getenv("HTTP_CLIENT_IP");
  178. if (empty($auth_ip)) {
  179. $auth_ip = getenv("HTTP_X_FORWARDED_FOR");
  180. if (empty($auth_ip)) {
  181. $auth_ip = getenv("REMOTE_ADDR");
  182. if (empty($auth_ip)) {
  183. $auth_ip = $_SERVER['REMOTE_ADDR'];
  184. }
  185. }
  186. }
  187. return $auth_ip;
  188. }
  189. function fbytes($traff)
  190. {
  191. $units_IEC = array(
  192. "",
  193. "Ki",
  194. "Mi",
  195. "Gi",
  196. "Ti"
  197. );
  198. $units_metric = array(
  199. "",
  200. "k",
  201. "M",
  202. "G",
  203. "T"
  204. );
  205. if (!empty($traff) and $traff > 0) {
  206. $KB = get_const('KB');
  207. if ($KB) {
  208. $KB = 1024;
  209. } else {
  210. $KB = 1000;
  211. }
  212. //IEC
  213. if ($KB == 1024) {
  214. $index = min(((int) log($traff, $KB)), count($units_IEC) - 1);
  215. $result = round($traff / pow($KB, $index), 3) . ' ' . $units_IEC[$index] . 'B';
  216. } else {
  217. $index = min(((int) log($traff, $KB)), count($units_metric) - 1);
  218. $result = round($traff / pow($KB, $index), 3) . ' ' . $units_metric[$index] . 'B';
  219. }
  220. } else {
  221. $result = '0 B';
  222. }
  223. return $result;
  224. }
  225. function fpkts($packets)
  226. {
  227. $units = array(
  228. "",
  229. "k",
  230. "M",
  231. "G",
  232. "T"
  233. );
  234. if (!empty($packets) and $packets > 0) {
  235. $index = min(((int) log($packets, 1000)), count($units) - 1);
  236. $result = round($packets / pow(1000, $index), 3) . ' ' . $units[$index] . 'pkt/s';
  237. } else {
  238. $result = '0 pkt/s';
  239. }
  240. return $result;
  241. }
  242. function checkValidIp($cidr)
  243. {
  244. if (!is_string($cidr) || empty(trim($cidr))) {
  245. return false;
  246. }
  247. $cidr = trim($cidr);
  248. // Проверяем IPv4 CIDR
  249. if (preg_match('/^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$/', $cidr)) {
  250. return validateIPv4CIDR($cidr);
  251. }
  252. // Проверяем IPv6 CIDR
  253. if (preg_match('/^([0-9a-fA-F:]+)+(\/\d{1,3})?$/i', $cidr)) {
  254. return validateIPv6CIDR($cidr);
  255. }
  256. return false;
  257. }
  258. function validateIPv4CIDR($cidr)
  259. {
  260. $parts = explode("/", $cidr);
  261. $ip = $parts[0];
  262. $netmask = isset($parts[1]) ? (int)$parts[1] : 32;
  263. // Проверяем октеты
  264. $octets = explode(".", $ip);
  265. if (count($octets) !== 4) {
  266. return false;
  267. }
  268. foreach ($octets as $octet) {
  269. $octet = (int)$octet;
  270. if ($octet < 0 || $octet > 255) {
  271. return false;
  272. }
  273. }
  274. return $netmask >= 0 && $netmask <= 32;
  275. }
  276. // для IPv6
  277. function validateIPv6CIDR($cidr)
  278. {
  279. // Упрощенная проверка IPv6
  280. $parts = explode("/", $cidr);
  281. $ip = $parts[0];
  282. $netmask = isset($parts[1]) ? (int)$parts[1] : 128;
  283. return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false
  284. && $netmask >= 0 && $netmask <= 128;
  285. }
  286. function normalizeIpAddress($input) {
  287. // Заменяем все возможные варианты "ю" на стандартные точки
  288. $normalized = str_replace(
  289. ['ю', 'Ю', '>'], // Кириллические и латинские варианты
  290. '.',
  291. strtolower(trim($input))
  292. );
  293. if (!checkValidIp($normalized)) { return ''; }
  294. return $normalized;
  295. }
  296. function checkValidMac($mac)
  297. {
  298. if (!is_string($mac)) return false;
  299. $mac = trim($mac);
  300. // Отдельные шаблоны для каждого формата
  301. $patterns = [
  302. '/^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/', // 00:1A:2B:3C:4D:5E
  303. '/^([0-9a-fA-F]{4}[\\.-]){2}[0-9a-fA-F]{4}$/', // 001A.2B3C.4D5E
  304. '/^[0-9A-Fa-f]{12}$/' // 001A2B3C4D5E
  305. ];
  306. foreach ($patterns as $pattern) {
  307. if (preg_match($pattern, $mac)) {
  308. return true;
  309. }
  310. }
  311. return false;
  312. }
  313. function checkValidHostname($dnsname)
  314. {
  315. if (empty($dnsname)) {
  316. return TRUE;
  317. }
  318. $host_pattern = "/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\.?$/";
  319. if (!preg_match($host_pattern, $dnsname)) {
  320. $result = FALSE;
  321. } else {
  322. $result = TRUE;
  323. }
  324. return $result;
  325. }
  326. function replaceSpecialChars($input) {
  327. // Заменяем ? на _ в любом месте
  328. $result = str_replace('?', '_', $input);
  329. // Заменяем * на % только в начале и конце с помощью регулярного выражения
  330. $result = preg_replace('/\*(?=.*.)/', '%', $result);
  331. return $result;
  332. }
  333. function searchHostname($db, $id, $hostname)
  334. {
  335. if (empty($hostname)) {
  336. return NULL;
  337. }
  338. $result = '';
  339. $domain_zone = get_option($db, 33);
  340. $a_search_filter = 'SELECT * FROM user_auth WHERE deleted=0 and id !="' . $id . '" and (dns_name ="' . db_escape($db, $hostname) . '" or dns_name ="' . db_escape($db, $hostname . '.' . $domain_zone) . '")';
  341. // LOG_DEBUG($db, "A search-filter: ".$a_search_filter);
  342. $a_records = get_records_sql($db, $a_search_filter);
  343. foreach ($a_records as $a_rec) {
  344. $result .= 'auth_id:' . $a_rec['id'] . ' ip: ' . $a_rec['ip'] . '; ';
  345. }
  346. if (!empty($result)) {
  347. $result = 'A-record: ' . $result;
  348. }
  349. $result_cname = '';
  350. $cname_search_filter = 'SELECT * FROM user_auth_alias WHERE auth_id !="' . $id . '" and (alias ="' . db_escape($db, $hostname) . '" or alias ="' . db_escape($db, $hostname . '.' . $domain_zone) . '")';
  351. // LOG_DEBUG($db, "CNAME search-filter: ".$cname_search_filter);
  352. $a_records = get_records_sql($db, $cname_search_filter);
  353. foreach ($a_records as $a_rec) {
  354. $result_cname .= 'auth_id:' . $a_rec['auth_id'] . ';';
  355. }
  356. if (!empty($result_cname)) {
  357. $result_cname = 'CNAME-record: ' . $result_cname;
  358. }
  359. $result = trim($result . ' ' . $result_cname);
  360. return $result;
  361. }
  362. function checkUniqHostname($db, $id, $hostname)
  363. {
  364. if (empty($hostname)) {
  365. return TRUE;
  366. }
  367. $domain_zone = get_option($db, 33);
  368. $check_A_filter = 'deleted=0 and id !="' . $id . '" and (dns_name ="' . db_escape($db, $hostname) . '" or dns_name ="' . db_escape($db, $hostname . '.' . $domain_zone) . '")';
  369. // LOG_DEBUG($db, "CNAME filter: ".$check_A_filter);
  370. $count = get_count_records($db, 'user_auth', $check_A_filter);
  371. if ($count > 0) {
  372. return FALSE;
  373. }
  374. $check_CNAME_filter = 'auth_id !="' . $id . '" and (alias ="' . db_escape($db, $hostname) . '" or alias ="' . db_escape($db, $hostname . '.' . $domain_zone) . '")';
  375. // LOG_DEBUG($db, "CNAME filter: ".$check_CNAME_filter);
  376. $count = get_count_records($db, 'user_auth_alias', $check_CNAME_filter);
  377. if ($count > 0) {
  378. return FALSE;
  379. }
  380. return TRUE;
  381. }
  382. // Транслитерация строк.
  383. function transliterate($string, $gost = false)
  384. {
  385. if ($gost) {
  386. $replace = array(
  387. "А" => "A",
  388. "а" => "a",
  389. "Б" => "B",
  390. "б" => "b",
  391. "В" => "V",
  392. "в" => "v",
  393. "Г" => "G",
  394. "г" => "g",
  395. "Д" => "D",
  396. "д" => "d",
  397. "Е" => "E",
  398. "е" => "e",
  399. "Ё" => "E",
  400. "ё" => "e",
  401. "Ж" => "Zh",
  402. "ж" => "zh",
  403. "З" => "Z",
  404. "з" => "z",
  405. "И" => "I",
  406. "и" => "i",
  407. "Й" => "I",
  408. "й" => "i",
  409. "К" => "K",
  410. "к" => "k",
  411. "Л" => "L",
  412. "л" => "l",
  413. "М" => "M",
  414. "м" => "m",
  415. "Н" => "N",
  416. "н" => "n",
  417. "О" => "O",
  418. "о" => "o",
  419. "П" => "P",
  420. "п" => "p",
  421. "Р" => "R",
  422. "р" => "r",
  423. "С" => "S",
  424. "с" => "s",
  425. "Т" => "T",
  426. "т" => "t",
  427. "У" => "U",
  428. "у" => "u",
  429. "Ф" => "F",
  430. "ф" => "f",
  431. "Х" => "Kh",
  432. "х" => "kh",
  433. "Ц" => "Tc",
  434. "ц" => "tc",
  435. "Ч" => "Ch",
  436. "ч" => "ch",
  437. "Ш" => "Sh",
  438. "ш" => "sh",
  439. "Щ" => "Shch",
  440. "щ" => "shch",
  441. "Ы" => "Y",
  442. "ы" => "y",
  443. "Э" => "E",
  444. "э" => "e",
  445. "Ю" => "Iu",
  446. "ю" => "iu",
  447. "Я" => "Ia",
  448. "я" => "ia",
  449. "ъ" => "",
  450. "ь" => ""
  451. );
  452. } else {
  453. $arStrES = array(
  454. "ае",
  455. "уе",
  456. "ое",
  457. "ые",
  458. "ие",
  459. "эе",
  460. "яе",
  461. "юе",
  462. "ёе",
  463. "ее",
  464. "ье",
  465. "ъе",
  466. "ый",
  467. "ий"
  468. );
  469. $arStrOS = array(
  470. "аё",
  471. "уё",
  472. "оё",
  473. "ыё",
  474. "иё",
  475. "эё",
  476. "яё",
  477. "юё",
  478. "ёё",
  479. "её",
  480. "ьё",
  481. "ъё",
  482. "ый",
  483. "ий"
  484. );
  485. $arStrRS = array(
  486. "а$",
  487. "у$",
  488. "о$",
  489. "ы$",
  490. "и$",
  491. "э$",
  492. "я$",
  493. "ю$",
  494. "ё$",
  495. "е$",
  496. "ь$",
  497. "ъ$",
  498. "@",
  499. "@"
  500. );
  501. $replace = array(
  502. "А" => "A",
  503. "а" => "a",
  504. "Б" => "B",
  505. "б" => "b",
  506. "В" => "V",
  507. "в" => "v",
  508. "Г" => "G",
  509. "г" => "g",
  510. "Д" => "D",
  511. "д" => "d",
  512. "Е" => "Ye",
  513. "е" => "e",
  514. "Ё" => "Ye",
  515. "ё" => "e",
  516. "Ж" => "Zh",
  517. "ж" => "zh",
  518. "З" => "Z",
  519. "з" => "z",
  520. "И" => "I",
  521. "и" => "i",
  522. "Й" => "Y",
  523. "й" => "y",
  524. "К" => "K",
  525. "к" => "k",
  526. "Л" => "L",
  527. "л" => "l",
  528. "М" => "M",
  529. "м" => "m",
  530. "Н" => "N",
  531. "н" => "n",
  532. "О" => "O",
  533. "о" => "o",
  534. "П" => "P",
  535. "п" => "p",
  536. "Р" => "R",
  537. "р" => "r",
  538. "С" => "S",
  539. "с" => "s",
  540. "Т" => "T",
  541. "т" => "t",
  542. "У" => "U",
  543. "у" => "u",
  544. "Ф" => "F",
  545. "ф" => "f",
  546. "Х" => "Kh",
  547. "х" => "kh",
  548. "Ц" => "Ts",
  549. "ц" => "ts",
  550. "Ч" => "Ch",
  551. "ч" => "ch",
  552. "Ш" => "Sh",
  553. "ш" => "sh",
  554. "Щ" => "Shch",
  555. "щ" => "shch",
  556. "Ъ" => "",
  557. "ъ" => "",
  558. "Ы" => "Y",
  559. "ы" => "y",
  560. "Ь" => "",
  561. "ь" => "",
  562. "Э" => "E",
  563. "э" => "e",
  564. "Ю" => "Yu",
  565. "ю" => "yu",
  566. "Я" => "Ya",
  567. "я" => "ya",
  568. "@" => "y",
  569. "$" => "ye"
  570. );
  571. $string = str_replace($arStrES, $arStrRS, $string);
  572. $string = str_replace($arStrOS, $arStrRS, $string);
  573. }
  574. return strtr($string, $replace);
  575. }
  576. function cidrToRange($cidr)
  577. {
  578. $range = array();
  579. $cidr = explode('/', $cidr);
  580. if (!isset($cidr[1])) {
  581. $cidr[1] = 32;
  582. }
  583. $start = (ip2long($cidr[0])) & ((-1 << (32 - (int) $cidr[1])));
  584. $stop = $start + pow(2, (32 - (int) $cidr[1])) - 1;
  585. $range[0] = long2ip($start);
  586. $range[1] = long2ip($stop);
  587. $range[2] = $cidr;
  588. //dhcp
  589. $dhcp_size = round(($stop - $start) / 2, PHP_ROUND_HALF_UP);
  590. $dhcp_start = $start + round($dhcp_size / 2, PHP_ROUND_HALF_UP);
  591. $range[3] = long2ip($dhcp_start);
  592. $range[4] = long2ip($dhcp_start + $dhcp_size);
  593. $range[5] = long2ip($start + 1);
  594. return $range;
  595. }
  596. function crypt_string($simple_string)
  597. {
  598. // Storin gthe cipher method
  599. $ciphering = "aes-128-cbc";
  600. // Using OpenSSl Encryption method
  601. $iv_length = openssl_cipher_iv_length($ciphering);
  602. $options = 0;
  603. // Using openssl_encrypt() function to encrypt the data
  604. return openssl_encrypt($simple_string, $ciphering, ENCRYPTION_KEY, $options, ENCRYPTION_IV);
  605. }
  606. function decrypt_string($crypted_string)
  607. {
  608. // Storin gthe cipher method
  609. $ciphering = "aes-128-cbc";
  610. // Using OpenSSl Encryption method
  611. $iv_length = openssl_cipher_iv_length($ciphering);
  612. $options = 0;
  613. // Using openssl_decrypt() function to decrypt the data
  614. return openssl_decrypt($crypted_string, $ciphering, ENCRYPTION_KEY, $options, ENCRYPTION_IV);
  615. }
  616. function print_instance_select($db, $instance_name, $instance_value)
  617. {
  618. print "<select id=\"$instance_name\" name=\"$instance_name\" >\n";
  619. $t_instance = get_records_sql($db, "SELECT id,name,description FROM filter_instances ORDER BY id");
  620. foreach ($t_instance as $row) {
  621. print_select_item($row['name'], $row['id'], $instance_value);
  622. }
  623. print "</select>\n";
  624. }
  625. function get_subnet_description($db, $subnet_id)
  626. {
  627. if (empty($subnet_id)) {
  628. return '';
  629. }
  630. $subnet = get_record_sql($db, 'SELECT * FROM subnets WHERE id=' . $subnet_id);
  631. if (empty($subnet)) {
  632. return '';
  633. }
  634. $result = $subnet['subnet'] . '&nbsp(' . $subnet['description'] . ')';
  635. return $result;
  636. }
  637. function get_filter_instance_description($db, $instance_id)
  638. {
  639. if (empty($instance_id)) {
  640. return '';
  641. }
  642. $instance = get_record_sql($db, 'SELECT * FROM filter_instances WHERE id=' . $instance_id);
  643. if (empty($instance)) {
  644. return '';
  645. }
  646. $result = $instance['name'] . '&nbsp(' . $instance['description'] . ')';
  647. return $result;
  648. }
  649. function print_add_gw_subnets($db, $device_id, $gs_name)
  650. {
  651. print "<select id=\"$gs_name\" name=\"$gs_name\" >\n";
  652. $t_gs = get_records_sql($db, "SELECT id,subnet,description FROM subnets WHERE subnets.free=0 AND subnets.id NOT IN (SELECT subnet_id FROM gateway_subnets WHERE gateway_subnets.device_id=" . $device_id . ") ORDER BY subnet");
  653. if (!empty($t_gs)) {
  654. foreach ($t_gs as $row) {
  655. print_select_item($row['subnet'] . '(' . $row['description'] . ')', $row['id'], 0);
  656. }
  657. }
  658. print "</select>\n";
  659. }
  660. function print_add_gw_instances($db, $device_id, $gs_name)
  661. {
  662. print "<select id=\"$gs_name\" name=\"$gs_name\" >\n";
  663. $t_gs = get_records_sql($db, "SELECT id,name,description FROM filter_instances WHERE filter_instances.id NOT IN (SELECT instance_id FROM device_filter_instances WHERE device_filter_instances.device_id=" . $device_id . ") ORDER BY name");
  664. if (!empty($t_gs)) {
  665. foreach ($t_gs as $row) {
  666. print_select_item($row['name'] . '(' . $row['description'] . ')', $row['id'], 0);
  667. }
  668. }
  669. print "</select>\n";
  670. }
  671. function print_add_dev_interface($db, $device_id, $int_list, $int_name)
  672. {
  673. print "&nbsp<select id=\"$int_name\" name=\"$int_name\" >\n";
  674. $t_int = get_records_sql($db, "SELECT * FROM device_l3_interfaces WHERE device_id=" . $device_id);
  675. $int_exists = [];
  676. if (!empty($t_int)) {
  677. foreach ($t_int as $interface) {
  678. $int_exists[$interface['snmpin']] = $interface;
  679. }
  680. }
  681. foreach ($int_list as $interface) {
  682. if (!empty($int_exists[$interface['index']])) {
  683. continue;
  684. }
  685. $value = $interface['name'] . ';' . $interface['index'] . ';' . $interface['type'];
  686. if ($interface['type'] == 1) {
  687. $interface['type'] = WEB_select_item_wan;
  688. }
  689. if ($interface['type'] == 0) {
  690. $interface['type'] = WEB_select_item_lan;
  691. }
  692. $display_str = $interface['name'] . '&nbsp|' . $interface['ip'] . '|' . $interface['type'];
  693. print_select_item($display_str, $value, 0);
  694. }
  695. print "</select>\n";
  696. }
  697. function print_ou_select_recursive($db, $ou_name, $ou_value, $parent_id = null, $level = 0, $hide_zero_id = false)
  698. {
  699. $conditions = [];
  700. if ($parent_id === null) {
  701. $conditions[] = "(parent_id IS NULL OR parent_id = 0)";
  702. } else {
  703. $conditions[] = "parent_id = " . (int)$parent_id;
  704. }
  705. if ($hide_zero_id) {
  706. $conditions[] = "id != 0";
  707. }
  708. $where = implode(" AND ", $conditions);
  709. $sql = "SELECT id, parent_id, ou_name FROM ou
  710. WHERE $where
  711. ORDER BY ou_name";
  712. $items = get_records_sql($db, $sql);
  713. if (empty($items)) {
  714. return;
  715. }
  716. foreach ($items as $row) {
  717. $indent = str_repeat("&nbsp;&nbsp;&nbsp;", $level);
  718. $prefix = ($level > 0) ? $indent . "-&nbsp;" : "";
  719. $display_name = $prefix . htmlspecialchars($row['ou_name']);
  720. print_select_item($display_name, $row['id'], $ou_value);
  721. print_ou_select_recursive($db, $ou_name, $ou_value, $row['id'], $level + 1, $hide_zero_id);
  722. }
  723. }
  724. function print_ou_select($db, $ou_name, $ou_value)
  725. {
  726. print "<select id=\"$ou_name\" name=\"$ou_name\" >\n";
  727. print_ou_select_recursive($db, $ou_name, $ou_value, null, 0, false);
  728. print "</select>\n";
  729. }
  730. function print_ou_set($db, $ou_name, $ou_value)
  731. {
  732. print "<select id=\"$ou_name\" name=\"$ou_name\" >\n";
  733. print_ou_select_recursive($db, $ou_name, $ou_value, null, 0, true);
  734. print "</select>\n";
  735. }
  736. function print_subnet_select($db, $subnet_name, $subnet_value)
  737. {
  738. print "<select id=\"$subnet_name\" name=\"$subnet_name\" >\n";
  739. $t_subnet = get_recrods_sql($db, "SELECT id,subnet FROM subnets ORDER BY ip_int_start");
  740. print_select_item(WEB_select_item_all_ips, 0, $subnet_value);
  741. if (!empty($t_subnet)) {
  742. foreach ($t_subnet as $row) {
  743. print_select_item($row['subnet'], $row['id'], $subnet_value);
  744. }
  745. }
  746. print "</select>\n";
  747. }
  748. function print_acl_select($db, $acl_name, $acl_value)
  749. {
  750. print "<select id=\"$acl_name\" name=\"$acl_name\" >\n";
  751. $t_acl = get_records_sql($db, "SELECT id,name FROM acl ORDER BY id");
  752. if (!empty($t_acl)) {
  753. foreach ($t_acl as $row) {
  754. print_select_item($row['name'], $row['id'], $acl_value);
  755. }
  756. }
  757. print "</select>\n";
  758. }
  759. function print_device_ip_select($db, $ip_name, $ip, $user_id)
  760. {
  761. print "<select id=\"$ip_name\" name=\"$ip_name\">\n";
  762. $auth_list = get_records_sql($db, "SELECT ip FROM user_auth WHERE user_id=$user_id AND deleted=0 ORDER BY ip_int");
  763. if (!empty($auth_list)) {
  764. foreach ($auth_list as $row) {
  765. print_select_item($row['ip'], $row['ip'], $ip);
  766. }
  767. }
  768. print "</select>\n";
  769. }
  770. function print_subnet_select_office($db, $subnet_name, $subnet_value)
  771. {
  772. print "<select id=\"$subnet_name\" name=\"$subnet_name\" >\n";
  773. $t_subnet = get_records_sql($db, "SELECT id,subnet FROM subnets WHERE office=1 ORDER BY ip_int_start");
  774. print_select_item(WEB_select_item_all_ips, 0, $subnet_value);
  775. if (!empty($t_subnet)) {
  776. foreach ($t_subnet as $row) {
  777. print_select_item($row['subnet'], $row['id'], $subnet_value);
  778. }
  779. }
  780. print "</select>\n";
  781. }
  782. function print_subnet_select_office_splitted($db, $subnet_name, $subnet_value)
  783. {
  784. print "<select id=\"$subnet_name\" name=\"$subnet_name\" >\n";
  785. $t_subnet = get_records_sql($db, "SELECT id,subnet,ip_int_start,ip_int_stop FROM subnets WHERE office=1 ORDER BY ip_int_start");
  786. print_select_item(WEB_select_item_all_ips, 0, $subnet_value);
  787. foreach ($t_subnet as $row) {
  788. print_select_item($row['subnet'], $row['subnet'], $subnet_value);
  789. $cidr = cidrToRange($row['subnet']);
  790. $f_start_ip = $row['ip_int_start'];
  791. $f_stop_ip = $row['ip_int_stop'];
  792. if ($cidr[2][1] < 24) {
  793. while ($f_start_ip <= $f_stop_ip) {
  794. print_select_item("&nbsp&nbsp-&nbsp" . long2ip($f_start_ip) . "/24", long2ip($f_start_ip) . "/24", $subnet_value);
  795. $f_start_ip += 256;
  796. }
  797. }
  798. }
  799. print "</select>\n";
  800. }
  801. function print_loglevel_select($item_name, $value)
  802. {
  803. print "<select id=\"$item_name\" name=\"$item_name\">\n";
  804. print_select_item('Error', L_ERROR, $value);
  805. print_select_item('Warning', L_WARNING, $value);
  806. print_select_item('Info', L_INFO, $value);
  807. print_select_item('Verbose', L_VERBOSE, $value);
  808. print_select_item('Debug', L_DEBUG, $value);
  809. print "</select>\n";
  810. }
  811. function print_timeshift_select($value)
  812. {
  813. print "<select id='date_shift' name='date_shift' onchange=\"updateDates()\">\n";
  814. print_select_item('-', '-', $value);
  815. print_select_item(WEB_date_shift_hour, 'h', $value);
  816. print_select_item(WEB_date_shift_8hour, '8h', $value);
  817. print_select_item(WEB_date_shift_day, 'd', $value);
  818. print_select_item(WEB_date_shift_month, 'm', $value);
  819. print "</select>\n";
  820. }
  821. function print_date_fields($date1,$date2,$date_shift)
  822. {
  823. print WEB_log_start_date.'&nbsp'; print '<input type="datetime-local" name="date_start" id="date_start" value="'.$date1.'" onchange="SetDateShiftCustom()"/>';
  824. print WEB_log_stop_date.'&nbsp'; print '<input type="datetime-local" name="date_stop" id="date_stop" value="'.$date2.'" onchange="SetDateShiftCustom()"/>';
  825. print WEB_date_shift.'&nbsp'; print_timeshift_select($date_shift);
  826. }
  827. function reencodeurl($url)
  828. {
  829. $url_arr = explode('?', $url);
  830. $fpage = $url_arr[0];
  831. if (isset($url_arr[1])) {
  832. $params = $url_arr[1];
  833. $params_arr = explode('&', $params);
  834. $new_params = '';
  835. foreach ($params_arr as $row) {
  836. $param = explode('=', $row);
  837. $key = $param[0];
  838. $value = urlencode(urldecode($param[1]));
  839. $new_params .= "&" . $key . "=" . $value;
  840. }
  841. $new_params = preg_replace('/^&/', '', $new_params);
  842. } else {
  843. $new_params = '=';
  844. }
  845. if ($new_params === '=') {
  846. $new_url = $fpage;
  847. } else {
  848. $new_url = $fpage . "?" . $new_params;
  849. }
  850. return $new_url;
  851. }
  852. function print_submenu_url($display_name, $page, $current_page, $last)
  853. {
  854. $url_arr = explode('?', $page);
  855. $fpage = $url_arr[0];
  856. $new_url = reencodeurl($page);
  857. if ($fpage === $current_page) {
  858. print "<b>$display_name</b>";
  859. } else {
  860. print "<a href='" . $new_url . "'> $display_name </a>";
  861. }
  862. if (!isset($last) or $last == 0) {
  863. print " | ";
  864. }
  865. }
  866. function print_submenu_nw($display_name, $page, $current_page, $last)
  867. {
  868. $url_arr = explode('?', $page);
  869. $fpage = $url_arr[0];
  870. $new_url = reencodeurl($page);
  871. if ($fpage === $current_page) {
  872. print "<b>$display_name</b>";
  873. } else {
  874. print '<a href="" onclick="window.open(\'' . $new_url . "', '_tab').focus(); return false;\">" . $display_name . "</a>";
  875. }
  876. if (!isset($last) or $last == 0) {
  877. print " | ";
  878. }
  879. }
  880. function print_url($display_name, $page)
  881. {
  882. print "<a href='" . reencodeurl($page) . "'> $display_name </a>";
  883. }
  884. function print_log_submenu($current_page)
  885. {
  886. print "<div id='submenu'>\n";
  887. print_submenu_url(WEB_submenu_dhcp_log, '/admin/logs/dhcp.php', $current_page, 0);
  888. print_submenu_url(WEB_submenu_work_log, '/admin/logs/index.php', $current_page, 0);
  889. print_submenu_url(WEB_submenu_mac_history, '/admin/logs/mac.php', $current_page, 0);
  890. print_submenu_url(WEB_submenu_ip_history, '/admin/logs/ip.php', $current_page, 0);
  891. print_submenu_url(WEB_submenu_mac_unknown, '/admin/logs/unknown.php', $current_page, 0);
  892. print_submenu_url(WEB_submenu_traffic, '/admin/logs/detaillog.php', $current_page, 0);
  893. print_submenu_url(WEB_submenu_syslog, '/admin/logs/syslog.php', $current_page, 1);
  894. print "</div>\n";
  895. }
  896. function print_control_submenu($current_page)
  897. {
  898. print "<div id='submenu'>\n";
  899. print_submenu_url(WEB_submenu_control, '/admin/customers/control.php', $current_page, 0);
  900. print_submenu_url(WEB_submenu_network, '/admin/customers/index-subnets.php', $current_page, 0);
  901. print_submenu_url(WEB_submenu_network_stats, '/admin/customers/control-subnets-usage.php', $current_page, 0);
  902. print_submenu_url(WEB_submenu_options, '/admin/customers/control-options.php', $current_page, 0);
  903. print_submenu_url(WEB_submenu_customers, '/admin/customers/index.php', $current_page, 0);
  904. print_submenu_url(WEB_submenu_buildings, '/admin/customers/building.php', $current_page, 0);
  905. print_submenu_url(WEB_submenu_device_models, '/admin/customers/devmodels.php', $current_page, 0);
  906. print_submenu_url(WEB_submenu_vendors, '/admin/customers/devvendors.php', $current_page, 1);
  907. print "</div>\n";
  908. }
  909. function print_filters_submenu($current_page)
  910. {
  911. print "<div id='submenu'>\n";
  912. print_submenu_url(WEB_submenu_filter_list, '/admin/filters/index.php', $current_page, 0);
  913. print_submenu_url(WEB_submenu_filter_group, '/admin/filters/groups.php', $current_page, 0);
  914. print_submenu_url(WEB_submenu_filter_instances, '/admin/filters/instances.php', $current_page, 1);
  915. print "</div>\n";
  916. }
  917. function print_reports_submenu($current_page)
  918. {
  919. print "<div id='submenu'>\n";
  920. print_submenu_url(WEB_submenu_traffic_ip_report, '/admin/reports/index-full.php', $current_page, 0);
  921. print_submenu_url(WEB_submenu_traffic_login_report, '/admin/reports/index.php', $current_page, 0);
  922. print_submenu_url(WEB_submenu_traffic_wan_report, '/admin/reports/wan.php', $current_page, 1);
  923. print "</div>\n";
  924. }
  925. function print_trafdetail_submenu($current_page, $params, $description)
  926. {
  927. print "<div id='subsubmenu'>\n";
  928. print "$description\n";
  929. print_submenu_url(WEB_submenu_traffic_top10, '/admin/reports/userdaydetail.php' . "?$params", $current_page, 0);
  930. print_submenu_url(WEB_submenu_detail_log, '/admin/reports/userdaydetaillog.php' . "?$params", $current_page, 1);
  931. print "</div>\n";
  932. }
  933. function print_device_submenu($current_page)
  934. {
  935. print "<div id='submenu'>\n";
  936. print_submenu_url(WEB_submenu_net_devices, '/admin/devices/index.php', $current_page, 0);
  937. print_submenu_url(WEB_submenu_passive_net_devices, '/admin/devices/index-passive.php', $current_page, 0);
  938. print_submenu_url(WEB_submenu_hierarchy, '/admin/devices/index-tree.php', $current_page, 0);
  939. print_submenu_url(WEB_submenu_ports_vlan, '/admin/devices/portsbyvlan.php', $current_page, 1);
  940. print "</div>\n";
  941. }
  942. function open_window_url($url)
  943. {
  944. return "window.open('" . $url . "', '_blank');";
  945. }
  946. function print_editdevice_submenu($current_page, $id, $dev_type, $dev_name = NULL)
  947. {
  948. print "<div id='subsubmenu'>\n";
  949. $dev_id = '';
  950. if (isset($id)) {
  951. $dev_id = '?id=' . $id;
  952. }
  953. if (!empty($dev_name)) {
  954. print "<b>" . $dev_name . "::</b>";
  955. }
  956. print_submenu_url(WEB_submenu_options, '/admin/devices/editdevice.php' . $dev_id, $current_page, 0);
  957. if ($dev_type <= 2) {
  958. print_submenu_url(WEB_submenu_ports, '/admin/devices/switchport.php' . $dev_id, $current_page, 0);
  959. print_submenu_url(WEB_submenu_state, '/admin/devices/switchstatus.php' . $dev_id, $current_page, 0);
  960. print_submenu_url(WEB_submenu_connections, '/admin/devices/switchport-conn.php' . $dev_id, $current_page, 1);
  961. }
  962. print "</div>\n";
  963. }
  964. function print_ip_submenu($current_page)
  965. {
  966. print "<div id='submenu'>\n";
  967. print_submenu_url(WEB_submenu_ip_list, '/admin/iplist/index.php', $current_page, 0);
  968. print_submenu_url(WEB_submenu_nagios, '/admin/iplist/nagios.php', $current_page, 0);
  969. print_submenu_url(WEB_submenu_doubles, '/admin/iplist/doubles.php', $current_page, 0);
  970. print_submenu_url(WEB_submenu_deleted, '/admin/iplist/deleted.php', $current_page, 0);
  971. print_submenu_url(WEB_submenu_auto_rules, '/admin/iplist/auto_rules.php', $current_page, 1);
  972. print "</div>\n";
  973. }
  974. function get_nagios_name($auth)
  975. {
  976. if (!empty($auth['dns_name'])) {
  977. return $auth['dns_name'];
  978. }
  979. if (!empty($auth['dhcp_hostname'])) {
  980. return $auth['dhcp_hostname'];
  981. }
  982. if (!empty($auth['description'])) {
  983. $result = transliterate($auth['description']);
  984. $result = preg_replace('/\(/', '-', $result);
  985. $result = preg_replace('/\)/', '-', $result);
  986. $result = preg_replace('/--/', '-', $result);
  987. return $result;
  988. }
  989. if (empty($auth['login'])) {
  990. $auth['login'] = 'host';
  991. }
  992. return $auth['login'] . "_" . $auth['id'];
  993. }
  994. function get_ou($db, $ou_value)
  995. {
  996. if (!isset($ou_value)) {
  997. return;
  998. }
  999. $ou_name = get_record_sql($db, "SELECT ou_name FROM ou WHERE id=$ou_value");
  1000. if (empty($ou_name)) {
  1001. return;
  1002. }
  1003. return $ou_name['ou_name'];
  1004. }
  1005. function get_device_model($db, $model_value)
  1006. {
  1007. if (!isset($model_value)) {
  1008. return;
  1009. }
  1010. $model_name = get_record_sql($db, "SELECT model_name FROM device_models WHERE id=$model_value");
  1011. if (empty($model_name)) {
  1012. return;
  1013. }
  1014. return $model_name['model_name'];
  1015. }
  1016. function get_device_model_name($db, $model_value)
  1017. {
  1018. if (!isset($model_value)) {
  1019. return '';
  1020. }
  1021. $model_name = get_record_sql($db, "SELECT M.id,M.model_name,V.name FROM device_models M,vendors V WHERE M.vendor_id = V.id AND M.id=$model_value");
  1022. if (empty($model_name)) {
  1023. return '';
  1024. }
  1025. return $model_name['name'] . ' ' . $model_name['model_name'];
  1026. }
  1027. function get_device_model_vendor($db, $model_value)
  1028. {
  1029. if (!isset($model_value)) {
  1030. return '';
  1031. }
  1032. $model_name = get_record_sql($db, "SELECT vendor_id FROM device_models WHERE id=$model_value");
  1033. if (empty($model_name)) {
  1034. return '';
  1035. }
  1036. return $model_name['vendor_id'];
  1037. }
  1038. function get_building($db, $building_value)
  1039. {
  1040. if (!isset($building_value)) {
  1041. return;
  1042. }
  1043. $building_name = get_record_sql($db, "SELECT name FROM building WHERE id=$building_value");
  1044. if (empty($building_name)) {
  1045. return;
  1046. }
  1047. return $building_name['name'];
  1048. }
  1049. function print_device_model_select($db, $device_model_name, $device_model_value)
  1050. {
  1051. print "<select id=\"$device_model_name\" name=\"$device_model_name\" class=\"js-select-single\">\n";
  1052. $t_device_model = get_records_sql($db, "SELECT M.id,M.model_name,V.name FROM device_models M,vendors V WHERE M.vendor_id = V.id ORDER BY V.name,M.model_name");
  1053. foreach ($t_device_model as $row) {
  1054. print_select_item($row['name'] . " " . $row['model_name'], $row['id'], $device_model_value);
  1055. }
  1056. print "</select>\n";
  1057. }
  1058. function print_filter_group_select($db, $group_name, $group_value)
  1059. {
  1060. print "<select id=\"$group_name\" name=\"$group_name\">\n";
  1061. $t_group = get_records_sql($db, "SELECT id,group_name FROM group_list ORDER BY group_name");
  1062. foreach ($t_group as $row) {
  1063. print_select_item($row['group_name'], $row['id'], $group_value);
  1064. }
  1065. print "</select>\n";
  1066. }
  1067. function print_building_select($db, $building_name, $building_value)
  1068. {
  1069. print "<select id=\"$building_name\" name=\"$building_name\">\n";
  1070. print_select_item(WEB_select_item_all, 0, $building_value);
  1071. $t_building = get_records_sql($db, "SELECT id,name FROM building ORDER BY name");
  1072. foreach ($t_building as $row) {
  1073. print_select_item($row['name'], $row['id'], $building_value);
  1074. }
  1075. print "</select>\n";
  1076. }
  1077. function print_devmodels_select($db, $devmodel_name, $devmodel_value, $dev_filter = 'device_type<=2')
  1078. {
  1079. print "<select id=\"$devmodel_name\" name=\"$devmodel_name\">\n";
  1080. print_select_item(WEB_select_item_all, -1, $devmodel_value);
  1081. $t_devmodel = get_records_sql($db, "SELECT M.id,V.name,M.model_name FROM device_models M,vendors V WHERE M.vendor_id = V.id and M.id in (SELECT device_model_id FROM devices WHERE $dev_filter) ORDER BY V.name,M.model_name");
  1082. if (!empty($t_devmodel)) {
  1083. foreach ($t_devmodel as $row) {
  1084. print_select_item($row['name'] . " " . $row['model_name'], $row['id'], $devmodel_value);
  1085. }
  1086. }
  1087. print "</select>\n";
  1088. }
  1089. function print_devtypes_select($db, $devtype_name, $devtype_value, $mode)
  1090. {
  1091. print "<select id=\"$devtype_name\" name=\"$devtype_name\">\n";
  1092. print_select_item(WEB_select_item_all, -1, $devtype_value);
  1093. $filter = '';
  1094. if (!empty($mode)) {
  1095. $filter = "WHERE $mode";
  1096. }
  1097. $t_devtype = get_records_sql($db, "SELECT id,name_" . HTML_LANG . " FROM device_types $filter ORDER BY name_" . HTML_LANG );
  1098. if (!empty($t_devtype)) {
  1099. foreach ($t_devtype as $row) {
  1100. print_select_item($row['name_' . HTML_LANG ], $row['id'], $devtype_value);
  1101. }
  1102. }
  1103. print "</select>\n";
  1104. }
  1105. function print_devtype_select($db, $devtype_name, $devtype_value)
  1106. {
  1107. print "<select id=\"$devtype_name\" name=\"$devtype_name\">\n";
  1108. $t_devtype = get_records_sql($db, "SELECT id,name_" . HTML_LANG . " FROM device_types ORDER BY name_" . HTML_LANG );
  1109. foreach ($t_devtype as $row) {
  1110. print_select_item($row['name_'.HTML_LANG], $row['id'], $devtype_value);
  1111. }
  1112. print "</select>\n";
  1113. }
  1114. function get_group($db, $group_value)
  1115. {
  1116. $group = get_record_sql($db, "SELECT group_name FROM group_list WHERE id=$group_value");
  1117. if (!empty($group) and isset($group['group_name'])) {
  1118. return $group['group_name'];
  1119. }
  1120. return '';
  1121. }
  1122. function get_devtype_name($db, $device_type_id)
  1123. {
  1124. $type = get_record_sql($db, "SELECT name_" . HTML_LANG . " FROM device_types WHERE id=$device_type_id");
  1125. if (!empty($type) and isset($type['name_'.HTML_LANG])) {
  1126. return $type['name_'.HTML_LANG];
  1127. }
  1128. return '';
  1129. }
  1130. function get_l3_interfaces($db, $device_id)
  1131. {
  1132. $wan = '';
  1133. $lan = '';
  1134. $t_l3int = get_records_sql($db, "SELECT name,interface_type FROM device_l3_interfaces WHERE device_id=$device_id ORDER BY name");
  1135. if (empty($t_l3int)) { return ''; }
  1136. foreach ($t_l3int as $row) {
  1137. if ($row['interface_type'] == 0) {
  1138. $lan = $lan . " " . $row['name'];
  1139. }
  1140. if ($row['interface_type'] == 1) {
  1141. $wan = $wan . " " . $row['name'];
  1142. }
  1143. }
  1144. $wan = trim($wan);
  1145. $lan = trim($lan);
  1146. $result = '';
  1147. if (!empty($wan)) {
  1148. $result .= ' WAN: ' . $wan . '<br>';
  1149. }
  1150. if (!empty($lan)) {
  1151. $result .= ' LAN: ' . $lan;
  1152. }
  1153. return trim($result);
  1154. }
  1155. function get_wan_interfaces($db, $device_id)
  1156. {
  1157. $device_id = (int)$device_id;
  1158. $l3_wan_sql = "SELECT id, name, snmpin
  1159. FROM device_l3_interfaces
  1160. WHERE device_id = '" . $device_id . "'
  1161. AND interface_type = 1
  1162. ORDER BY name";
  1163. $t_l3int = get_records_sql($db, $l3_wan_sql);
  1164. // Обрабатываем каждый интерфейс
  1165. foreach ($t_l3int as &$row) { // & - передача по ссылке для изменения исходного массива
  1166. $row['description'] = '';
  1167. if (empty($row['snmpin'])) {
  1168. continue;
  1169. }
  1170. $con_sql = "SELECT * FROM device_ports
  1171. WHERE device_id = '" . $device_id . "'
  1172. AND snmp_index = '" . $row['snmpin'] . "'";
  1173. $conn = get_record_sql($db, $con_sql);
  1174. // Проверяем, есть ли комментарий в результатах запроса
  1175. if (!empty($conn) && !empty($conn['description'])) {
  1176. $row['description'] = $conn['description'];
  1177. }
  1178. }
  1179. unset($row);
  1180. return $t_l3int;
  1181. }
  1182. function get_gw_subnets($db, $device_id)
  1183. {
  1184. $gw_subnets_sql = 'SELECT gateway_subnets.*,subnets.subnet,subnets.description FROM gateway_subnets LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id WHERE gateway_subnets.device_id=' . $device_id . ' ORDER BY subnets.subnet ASC';
  1185. $gw_subnets = get_records_sql($db, $gw_subnets_sql);
  1186. if (empty($gw_subnets)) { return ''; }
  1187. $result = '';
  1188. foreach ($gw_subnets as $row) {
  1189. if (!empty($row)) {
  1190. $result .= ' ' . $row['subnet'] . '<br>';
  1191. }
  1192. }
  1193. return trim($result);
  1194. }
  1195. function print_queue_select($db, $queue_name, $queue_value)
  1196. {
  1197. print "<select id=\"$queue_name\" name=\"$queue_name\">\n";
  1198. $t_queue = get_records_sql($db, "SELECT id,queue_name FROM queue_list ORDER BY queue_name");
  1199. foreach ($t_queue as $row) {
  1200. print_select_item($row['queue_name'], $row['id'], $queue_value);
  1201. }
  1202. print "</select>\n";
  1203. }
  1204. function get_queue($db, $queue_value)
  1205. {
  1206. $queue=get_record_sql($db, "SELECT queue_name FROM queue_list WHERE id=$queue_value");
  1207. if (!empty($queue) && isset($queue['queue_name'])) {
  1208. return $queue['queue_name'];
  1209. }
  1210. return '';
  1211. }
  1212. function print_qa_l3int_select($qa_name, $qa_value = 0)
  1213. {
  1214. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1215. print_select_item(WEB_select_item_lan, 0, $qa_value);
  1216. print_select_item(WEB_select_item_wan, 1, $qa_value);
  1217. print "</select>\n";
  1218. }
  1219. function print_qa_rule_select($qa_name, $qa_value = 1)
  1220. {
  1221. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1222. print_select_item('Subnet', 1, $qa_value);
  1223. print_select_item('Mac', 2, $qa_value);
  1224. print_select_item('Hostname', 3, $qa_value);
  1225. print "</select>\n";
  1226. }
  1227. function print_snmp_auth_proto_select($qa_name, $qa_value = 'sha512')
  1228. {
  1229. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1230. print_select_item('sha512', 'sha512', $qa_value);
  1231. print_select_item('sha256', 'sha256', $qa_value);
  1232. print_select_item('sha', 'sha', $qa_value);
  1233. print_select_item('md5', 'md5', $qa_value);
  1234. print "</select>\n";
  1235. }
  1236. function print_snmp_priv_proto_select($qa_name, $qa_value = 'aes128')
  1237. {
  1238. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1239. print_select_item('aes128', 'aes128', $qa_value);
  1240. print_select_item('aes', 'aes', $qa_value);
  1241. print_select_item('des', 'des', $qa_value);
  1242. print "</select>\n";
  1243. }
  1244. function get_int($qa_value = 0)
  1245. {
  1246. if (empty($qa_value)) {
  1247. $qa_value = 0;
  1248. } else {
  1249. $qa_value = (int)$qa_value * 1;
  1250. }
  1251. return $qa_value;
  1252. }
  1253. function print_qa_select($qa_name, $qa_value = 0)
  1254. {
  1255. print "<select name=\"$qa_name\" id=\"$qa_name\">\n";
  1256. if (empty($qa_value)) {
  1257. $qa_value = 0;
  1258. } else {
  1259. $qa_value = $qa_value * 1;
  1260. }
  1261. print_select_item(WEB_select_item_yes, 1, $qa_value);
  1262. print_select_item(WEB_select_item_no, 0, $qa_value);
  1263. print "</select>\n";
  1264. }
  1265. function print_list_select($qa_name, $qa_value, $list)
  1266. {
  1267. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1268. if (empty($qa_value)) {
  1269. $qa_value = '';
  1270. }
  1271. for ($i = 0; $i < count($list); ++$i) {
  1272. print_select_item($list[$i], $list[$i], $qa_value);
  1273. }
  1274. print "</select>\n";
  1275. }
  1276. function print_qa_select_ext($qa_name, $qa_value = 0, $readonly = 1)
  1277. {
  1278. $state = '';
  1279. if ($readonly) {
  1280. $state = 'disabled=true';
  1281. }
  1282. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1283. print_select_item_ext(WEB_select_item_yes, 1, $qa_value, $readonly);
  1284. print_select_item_ext(WEB_select_item_no, 0, $qa_value, $readonly);
  1285. print "</select>\n";
  1286. }
  1287. function print_td_yes_no($qa_value = 0, $text = FALSE)
  1288. {
  1289. $cl = 'down';
  1290. if ($qa_value == 1) { $cl = 'up'; }
  1291. // $cl = 'data';
  1292. if ($text) {
  1293. print "<td class=\"$cl\">";
  1294. if ($qa_value == 1) { print WEB_select_item_yes; } else { print WEB_select_item_no; }
  1295. print "</td>\n";
  1296. } else { print_td_qa($qa_value,FALSE,$cl); }
  1297. }
  1298. function print_yes_no($qa_value = 0, $yes_style = 'data', $no_style='data')
  1299. {
  1300. if ($qa_value) { $cl = $yes_style; } else { $cl = $no_style; }
  1301. print "<td class=\"$cl\">";
  1302. if ($qa_value == 1) {
  1303. print WEB_select_item_yes;
  1304. } else {
  1305. print WEB_select_item_no;
  1306. }
  1307. print "</td>\n";
  1308. }
  1309. function print_control_proto_select($qa_name, $qa_value = -1)
  1310. {
  1311. print "<select name=\"$qa_name\">\n";
  1312. print_select_item('Disabled', -1, $qa_value);
  1313. print_select_item('Ssh', 0, $qa_value);
  1314. print_select_item('Telnet', 1, $qa_value);
  1315. // print_select_item('Mikrotik rest api', 2, $qa_value);
  1316. print "</select>\n";
  1317. }
  1318. function print_snmp_select($qa_name, $qa_value = 0)
  1319. {
  1320. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1321. print_select_item('Disabled', 0, $qa_value);
  1322. print_select_item('v1', 1, $qa_value);
  1323. print_select_item('v2', 2, $qa_value);
  1324. print_select_item('v3', 3, $qa_value);
  1325. print "</select>\n";
  1326. }
  1327. function print_dhcp_select($qa_name, $qa_value = 0)
  1328. {
  1329. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1330. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1331. $qa_value = 'all';
  1332. }
  1333. print_select_item(WEB_select_item_events, 'all', $qa_value);
  1334. print_select_item(WEB_select_item_lease, 'add', $qa_value);
  1335. print_select_item(WEB_select_item_lease_refresh, 'old', $qa_value);
  1336. print_select_item(WEB_select_item_lease_free, 'del', $qa_value);
  1337. print "</select>\n";
  1338. }
  1339. function print_nagios_handler_select($db,$qa_name)
  1340. {
  1341. $nagios_handler = get_records_sql($db,"SELECT DISTINCT nagios_handler FROM user_auth WHERE nagios_handler IS NOT NULL AND nagios_handler != '' AND deleted=0");
  1342. if (!empty($nagios_handler) and count($nagios_handler)>0) {
  1343. print "<select name=\"$qa_name\">\n";
  1344. print_select_simple(WEB_select_item_no, '');
  1345. foreach ($nagios_handler as $handler) {
  1346. print_select_simple($handler['nagios_handler'],$handler['nagios_handler']);
  1347. }
  1348. print "</select>\n";
  1349. } else {
  1350. print "<input type=\"text\" name=\"$qa_name\" value=\"\" size=10/>";
  1351. }
  1352. }
  1353. function print_dhcp_acl($db,$qa_name)
  1354. {
  1355. $dhcp_acl = get_records_sql($db,"SELECT DISTINCT dhcp_acl FROM user_auth WHERE dhcp_acl IS NOT NULL AND dhcp_acl != '' AND deleted=0");
  1356. if (!empty($dhcp_acl) and count($dhcp_acl)>0) {
  1357. print "<select name=\"$qa_name\">\n";
  1358. print_select_simple(WEB_select_item_no, '');
  1359. foreach ($dhcp_acl as $acl) {
  1360. print_select_simple($acl['dhcp_acl'],$acl['dhcp_acl']);
  1361. }
  1362. print "</select>\n";
  1363. } else {
  1364. print "<input type=\"text\" name=\"$qa_name\" value=\"\" size=10/>";
  1365. }
  1366. }
  1367. function print_dhcp_option_set($db,$qa_name)
  1368. {
  1369. $dhcp_option_sets = get_records_sql($db,"SELECT DISTINCT dhcp_option_set FROM user_auth WHERE dhcp_option_set IS NOT NULL AND dhcp_option_set != '' AND deleted=0");
  1370. if (!empty($dhcp_option_sets) and count($dhcp_option_sets)>0) {
  1371. print "<select name=\"$qa_name\">\n";
  1372. print_select_simple(WEB_select_item_no, '');
  1373. foreach ($dhcp_option_sets as $dhcp_option_set) {
  1374. print_select_simple($dhcp_option_set['dhcp_option_set'],$dhcp_option_set['dhcp_option_set']);
  1375. }
  1376. print "</select>\n";
  1377. } else {
  1378. print "<input type=\"text\" name=\"$qa_name\" value=\"\" size=10/>";
  1379. }
  1380. }
  1381. function print_dhcp_acl_list($db,$qa_name,$value='')
  1382. {
  1383. $dhcp_acl = get_records_sql($db,"SELECT DISTINCT dhcp_acl FROM user_auth WHERE dhcp_acl IS NOT NULL AND dhcp_acl != '' AND deleted=0");
  1384. if (!empty($dhcp_acl) and count($dhcp_acl)>0) {
  1385. print "<input list=\"dhcp_acl\" id=\"$qa_name\" name=\"$qa_name\" value=\"$value\"/>";
  1386. print "<datalist id=\"dhcp_acl\">";
  1387. print "<option value=\"\">";
  1388. foreach ($dhcp_acl as $acl) {
  1389. print "<option value=\"{$acl['dhcp_acl']}\">";
  1390. }
  1391. print "</datalist>";
  1392. } else {
  1393. print "<input type=\"text\" name=\"$qa_name\" value=\"\" size=10/>";
  1394. }
  1395. }
  1396. function print_dhcp_option_set_list($db,$qa_name,$value='')
  1397. {
  1398. $dhcp_option_sets = get_records_sql($db,"SELECT DISTINCT dhcp_option_set FROM user_auth WHERE dhcp_option_set IS NOT NULL AND dhcp_option_set != '' AND deleted=0");
  1399. if (!empty($dhcp_option_sets) and count($dhcp_option_sets)>0) {
  1400. print "<input list=\"dhcp_option_set\" id=\"$qa_name\" name=\"$qa_name\" value=\"$value\"/>";
  1401. print "<datalist id=\"dhcp_option_set\">";
  1402. print "<option value=\"\">";
  1403. foreach ($dhcp_option_sets as $dhcp_option_set) {
  1404. print "<option value=\"{$dhcp_option_set['dhcp_option_set']}\">";
  1405. }
  1406. print "</datalist>";
  1407. } else {
  1408. print "<input type=\"text\" name=\"$qa_name\" value=\"\" size=10/>";
  1409. }
  1410. }
  1411. function print_enabled_select($qa_name, $qa_value)
  1412. {
  1413. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1414. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1415. $qa_value = 0;
  1416. }
  1417. print_select_item('-', 0, $qa_value);
  1418. print_select_item(WEB_select_item_disabled, 1, $qa_value);
  1419. print_select_item(WEB_select_item_enabled, 2, $qa_value);
  1420. print "</select>\n";
  1421. }
  1422. function print_rule_target_select($qa_name, $qa_value)
  1423. {
  1424. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1425. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1426. $qa_value = 0;
  1427. }
  1428. print_select_item('-', 0, $qa_value);
  1429. print_select_item(WEB_rules_target_user, 1, $qa_value);
  1430. print_select_item(WEB_rules_target_group, 2, $qa_value);
  1431. print "</select>\n";
  1432. }
  1433. function print_rule_type_select($qa_name, $qa_value)
  1434. {
  1435. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1436. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1437. $qa_value = 0;
  1438. }
  1439. print_select_item('-', 0, $qa_value);
  1440. print_select_item(WEB_rules_type_subnet, 1, $qa_value);
  1441. print_select_item(WEB_rules_type_mac, 2, $qa_value);
  1442. print_select_item(WEB_rules_type_hostname, 3, $qa_value);
  1443. print "</select>\n";
  1444. }
  1445. function print_yn_select($qa_name, $qa_value)
  1446. {
  1447. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1448. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1449. $qa_value = 0;
  1450. }
  1451. print_select_item('-', 0, $qa_value);
  1452. print_select_item(WEB_select_item_yes, 1, $qa_value);
  1453. print_select_item(WEB_select_item_no, 2, $qa_value);
  1454. print "</select>\n";
  1455. }
  1456. function print_ip_type_select($qa_name, $qa_value)
  1457. {
  1458. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1459. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1460. $qa_value = 0;
  1461. }
  1462. print_select_item(WEB_select_item_every, 0, $qa_value);
  1463. print_select_item(WEB_select_item_static, 1, $qa_value);
  1464. print_select_item(WEB_select_item_dhcp, 2, $qa_value);
  1465. print_select_item(WEB_select_item_suspicious, 3, $qa_value);
  1466. print "</select>\n";
  1467. }
  1468. function print_vendor_select($db, $qa_name, $qa_value)
  1469. {
  1470. print "<select id=\"$qa_name\" name=\"$qa_name\" style=\"width: 100%\">\n";
  1471. $sSQL = "SELECT id,name FROM vendors ORDER BY name";
  1472. $vendors = get_records_sql($db, $sSQL);
  1473. print_select_item(WEB_select_item_all, 0, $qa_value);
  1474. foreach ($vendors as $row) {
  1475. print_select_item($row['name'], $row['id'], $qa_value);
  1476. }
  1477. print "</select>\n";
  1478. }
  1479. function print_vendor_set($db, $qa_name, $qa_value)
  1480. {
  1481. print "<select id=\"$qa_name\" name=\"$qa_name\" style=\"width: 100%\">\n";
  1482. $sSQL = "SELECT id,name FROM vendors ORDER BY name";
  1483. $vendors = get_records_sql($db, $sSQL);
  1484. foreach ($vendors as $row) {
  1485. print_select_item($row['name'], $row['id'], $qa_value);
  1486. }
  1487. print "</select>\n";
  1488. }
  1489. function get_vendor_name($db, $v_id)
  1490. {
  1491. $vendor = get_record_sql($db, "SELECT * FROM vendors WHERE id=" . $v_id);
  1492. if (!empty($vendor) and isset($vendor['name'])) {
  1493. return $vendor['name'];
  1494. }
  1495. return '';
  1496. }
  1497. function get_qa($qa_value, $text = FALSE)
  1498. {
  1499. if ($text) {
  1500. if ($qa_value == 1) { return "Да"; }
  1501. return "Нет";
  1502. } else {
  1503. if ($qa_value == 1) { return '<span style="font-size: 24px; font-weight: bold;">✓</span>'; }
  1504. return '<span style="font-size: 24px; font-weight: bold;">✗</span>';
  1505. }
  1506. }
  1507. function get_yes($qa_value, $text = FALSE)
  1508. {
  1509. if ($text) {
  1510. if ($qa_value == 1) { return "Да"; }
  1511. return "";
  1512. } else {
  1513. if ($qa_value == 1) { return '<span style="font-size: 16px; font-weight: bold;">✓</span>'; }
  1514. return "";
  1515. }
  1516. }
  1517. function print_td_qa ($qa_value, $text = FALSE, $parent_class = '')
  1518. {
  1519. $cl = "data_green";
  1520. if (!$qa_value) { $cl = "data_red"; }
  1521. print "<td class=\"$parent_class $cl\" >" . get_qa($qa_value,$text) . "</td>";
  1522. }
  1523. function print_td_yes ($qa_value, $text = FALSE, $parent_class = '')
  1524. {
  1525. $cl = "data_green";
  1526. if (!$qa_value) { $cl = "data_red"; }
  1527. print "<td class=\"$parent_class $cl\" >" . get_yes($qa_value,$text) . "</td>";
  1528. }
  1529. function print_action_select($action_name, $action_value)
  1530. {
  1531. print "<select id=\"$action_name\" name=\"$action_name\">\n";
  1532. print_select_item(WEB_select_item_allow, 1, $action_value);
  1533. print_select_item(WEB_select_item_forbidden, 0, $action_value);
  1534. print "</select>\n";
  1535. }
  1536. function get_action($action_value)
  1537. {
  1538. if ($action_value == 1) {
  1539. return "Разрешить";
  1540. }
  1541. return "Запретить";
  1542. }
  1543. function print_filter_select($db, $filter_name, $group_id)
  1544. {
  1545. print "<select id=\"$filter_name\" name=\"$filter_name\" class=\"js-select-single\">\n";
  1546. if (isset($group_id)) {
  1547. $sSQL = "SELECT id,name FROM filter_list WHERE filter_list.id not in (Select filter_id FROM group_filters WHERE group_id=$group_id)";
  1548. } else {
  1549. $sSQL = "SELECT id,name FROM filter_list ORDER BY name";
  1550. }
  1551. $t_filters = get_records_sql($db, $sSQL);
  1552. foreach ($t_filters as $row) {
  1553. print_select_item($row['name'], $row['id'], 0);
  1554. }
  1555. print "</select>\n";
  1556. }
  1557. function get_filter($db, $filter_value)
  1558. {
  1559. $filter = get_record_sql($db, "SELECT name FROM filter_list WHERE id=" . $filter_value);
  1560. if (!empty($filter) and isset($filter['name'])) { return $filter['name']; }
  1561. return '';
  1562. }
  1563. function get_login($db, $user_id)
  1564. {
  1565. $login = get_record_sql($db, "SELECT login FROM user_list WHERE id=$user_id");
  1566. if (!empty($login) and isset($login['login'])) { return $login['login']; }
  1567. return '';
  1568. }
  1569. function get_auth_count($db, $user_id)
  1570. {
  1571. $count = get_record_sql($db, "SELECT count(id) as cnt FROM user_auth WHERE user_id=$user_id and deleted=0");
  1572. if (!empty($count) and isset($count['cnt'])) { return $count['cnt']; }
  1573. return 0;
  1574. }
  1575. function print_login_select($db, $login_name, $current_login)
  1576. {
  1577. print "<select id=\"$login_name\" name=\"$login_name\" class=\"js-select-single\">\n";
  1578. $t_login = get_records_sql($db, "SELECT id,login FROM user_list ORDER BY login");
  1579. print_select_item('None', 0, $current_login);
  1580. foreach ($t_login as $row) {
  1581. print_select_item($row['login'], $row['id'], $current_login);
  1582. }
  1583. print "</select>\n";
  1584. }
  1585. function print_auth_select($db, $login_name, $current_auth)
  1586. {
  1587. print "<select id=\"$login_name\" name=\"$login_name\" class=\"js-select-single\">\n";
  1588. $t_login = get_records_sql($db, "SELECT U.login,U.fio,A.ip,A.id FROM user_list as U, user_auth as A WHERE A.user_id=U.id and A.deleted=0 and (A.id not in (select device_ports.auth_id FROM device_ports) or A.id=$current_auth) ORDER BY U.login,U.fio,A.ip");
  1589. print_select_item('Empty', 0, $current_auth);
  1590. foreach ($t_login as $row) {
  1591. print_select_item($row['login'] . "[" . $row['fio'] . "] - " . $row['ip'], $row['id'], $current_auth);
  1592. }
  1593. print "</select>\n";
  1594. }
  1595. function print_auth_select_mac($db, $login_name, $current_auth)
  1596. {
  1597. print "<select id=\"$login_name\" name=\"$login_name\" class=\"js-select-single\">\n";
  1598. $t_login = get_records_sql($db, "SELECT U.login,U.fio,A.ip,A.mac,A.id FROM user_list as U, user_auth as A WHERE A.user_id=U.id and A.deleted=0 and (A.id not in (select device_ports.auth_id FROM device_ports) or A.id=$current_auth) ORDER BY U.login,U.fio,A.ip");
  1599. print_select_item('Empty', 0, $current_auth);
  1600. foreach ($t_login as $row) {
  1601. print_select_item($row['login'] . "[" . $row['mac'] . "] - " . $row['ip'], $row['id'], $current_auth);
  1602. }
  1603. print "</select>\n";
  1604. }
  1605. function compact_port_name($port)
  1606. {
  1607. $result = $port;
  1608. $result = preg_replace('/XGigabitEthernet/', 'X', $result);
  1609. $result = preg_replace('/TenGigabitEthernet/', 'Te', $result);
  1610. $result = preg_replace('/GigabitEthernet/', 'Gi', $result);
  1611. return $result;
  1612. }
  1613. function print_device_port_select($db, $field_name, $device_id, $target_id)
  1614. {
  1615. print "<select id=\"$field_name\" name=\"$field_name\" class=\"js-select-single\" >\n";
  1616. if (empty($target_id)) {
  1617. $target_id = 0;
  1618. }
  1619. if (empty($device_id)) {
  1620. $device_id = 0;
  1621. }
  1622. $d_sql = "SELECT D.device_name, DP.port, DP.device_id, DP.id, DP.ifName FROM devices AS D, device_ports AS DP WHERE D.deleted=0 and D.id = DP.device_id AND (DP.device_id<>$device_id or DP.id=$target_id) and (DP.id not in (select target_port_id FROM device_ports WHERE target_port_id>0 and target_port_id<>$target_id)) ORDER BY D.device_name,DP.port";
  1623. $t_device = get_records_sql($db, $d_sql);
  1624. print_select_item('Empty', 0, $target_id);
  1625. foreach ($t_device as $row) {
  1626. if (empty($row['ifName'])) {
  1627. $row['ifName'] = $row['port'];
  1628. }
  1629. print_select_item($row['device_name'] . "[" . $row['port'] . "] - " . compact_port_name($row['ifName']), $row['id'], $target_id);
  1630. }
  1631. print "</select>\n";
  1632. }
  1633. function print_device_select($db, $field_name, $device_id)
  1634. {
  1635. print "<select id=\"$field_name\" name=\"$field_name\" class=\"js-select-single\" >\n";
  1636. $d_sql = "SELECT D.device_name, D.id FROM devices AS D Where D.deleted=0 ORDER BY D.device_name ASC";
  1637. $t_device = get_records_sql($db, $d_sql);
  1638. print_select_item(WEB_select_item_every, 0, $device_id);
  1639. foreach ($t_device as $row) {
  1640. print_select_item($row['device_name'], $row['id'], $device_id);
  1641. }
  1642. print "</select>\n";
  1643. }
  1644. function print_netdevice_select($db, $field_name, $device_id)
  1645. {
  1646. print "<select id=\"$field_name\" name=\"$field_name\" class=\"js-select-single\" >\n";
  1647. $d_sql = "SELECT D.device_name, D.id FROM devices AS D Where D.deleted=0 and D.device_type<=2 ORDER BY D.device_name ASC";
  1648. $t_device = get_records_sql($db, $d_sql);
  1649. print_select_item(WEB_select_item_every, 0, $device_id);
  1650. foreach ($t_device as $row) {
  1651. print_select_item($row['device_name'], $row['id'], $device_id);
  1652. }
  1653. print "</select>\n";
  1654. }
  1655. function print_vlan_select($db, $field_name, $vlan)
  1656. {
  1657. print "<select id=\"$field_name\" name=\"$field_name\" class=\"js-select-single\" style=\"width: 100px;\" >\n";
  1658. $d_sql = "SELECT DISTINCT vlan FROM device_ports ORDER BY vlan DESC";
  1659. $v_device = get_records_sql($db, $d_sql);
  1660. if (!isset($vlan) or empty($vlan)) {
  1661. $vlan = 1;
  1662. };
  1663. print_select_item('1', 1, $vlan);
  1664. foreach ($v_device as $row) {
  1665. if ($row['vlan'] === '1') {
  1666. continue;
  1667. }
  1668. print_select_item($row['vlan'], $row['vlan'], $vlan);
  1669. }
  1670. print "</select>\n";
  1671. }
  1672. function print_device_select_ip($db, $field_name, $device_ip)
  1673. {
  1674. print "<select id=\"$field_name\" name=\"$field_name\" class=\"js-select-single\" >\n";
  1675. $d_sql = "SELECT D.device_name, D.ip FROM devices AS D Where D.deleted=0 ORDER BY D.device_name ASC";
  1676. $t_device = get_records_sql($db, $d_sql);
  1677. print_select_item(WEB_select_item_every, '', $device_ip);
  1678. foreach ($t_device as $row) {
  1679. print_select_item($row['device_name'], $row['ip'], $device_ip);
  1680. }
  1681. print "</select>\n";
  1682. }
  1683. function print_syslog_device_select($db, $field_name, $syslog_filter, $device_ip)
  1684. {
  1685. print "<select id=\"$field_name\" name=\"$field_name\" class=\"js-select-single\" >\n";
  1686. $d_sql = "SELECT R.ip, D.device_name FROM (SELECT DISTINCT ip FROM remote_syslog WHERE $syslog_filter) AS R LEFT JOIN (SELECT ip, device_name FROM devices WHERE deleted=0) AS D ON R.ip=D.ip ORDER BY R.ip ASC";
  1687. $t_device = get_records_sql($db, $d_sql);
  1688. print_select_item(WEB_select_item_every, '', $device_ip);
  1689. foreach ($t_device as $row) {
  1690. if (!isset($row['device_name']) or empty($row['device_name'])) {
  1691. $row['device_name'] = $row['ip'];
  1692. }
  1693. print_select_item($row['device_name'], $row['ip'], $device_ip);
  1694. }
  1695. print "</select>\n";
  1696. }
  1697. function print_gateway_select($db, $field_name, $device_id)
  1698. {
  1699. print "<select id=\"$field_name\" name=\"$field_name\" >\n";
  1700. $d_sql = "SELECT D.device_name, D.id FROM devices AS D Where D.deleted=0 and D.device_type=2 ORDER BY D.device_name ASC";
  1701. $t_device = get_records_sql($db, $d_sql);
  1702. print_select_item(WEB_select_item_every, 0, $device_id);
  1703. foreach ($t_device as $row) {
  1704. print_select_item($row['device_name'], $row['id'], $device_id);
  1705. }
  1706. print "</select>\n";
  1707. }
  1708. function get_gateways($db)
  1709. {
  1710. $d_sql = "SELECT D.device_name, D.id FROM devices AS D Where D.deleted=0 and D.device_type=2 ORDER BY D.device_name ASC";
  1711. $t_device = get_records_sql($db, $d_sql);
  1712. unset($result);
  1713. foreach ($t_device as $row) {
  1714. $result[$row['id']] = $row['device_name'];
  1715. }
  1716. return $result;
  1717. }
  1718. function print_device_port($db, $target_id)
  1719. {
  1720. $d_sql = "SELECT D.device_name, DP.port, DP.device_id FROM devices AS D, device_ports AS DP WHERE D.id = DP.device_id AND DP.id=$target_id and D.deleted=0";
  1721. $t_device = get_records_sql($db, $d_sql);
  1722. foreach ($t_device as $row) {
  1723. print "<a href=\"/admin/devices/switchport.php?id=".$row['device_id']."\">" . $row['device_name'] . "[" . $row['port'] . "]</a>\n";
  1724. }
  1725. }
  1726. function get_device_ips($db, $device_id)
  1727. {
  1728. $switch = get_record($db, 'devices', 'id=' . $device_id);
  1729. $index = 0;
  1730. if (!empty($switch['user_id'])) {
  1731. $auth_ips = get_records($db, 'user_auth', 'deleted=0 and user_id=' . $switch['user_id']);
  1732. foreach ($auth_ips as $key => $value) {
  1733. if (isset($value['ip'])) {
  1734. $result[$index] = $value['ip'];
  1735. $index++;
  1736. }
  1737. }
  1738. } else {
  1739. if (isset($switch['ip'])) {
  1740. $result[$index] = $switch['ip'];
  1741. $index++;
  1742. }
  1743. }
  1744. return $result;
  1745. }
  1746. function get_device_id($db, $device_name)
  1747. {
  1748. $d_sql = "SELECT id FROM devices WHERE device_name='$device_name' and deleted=0";
  1749. $dev = get_record_sql($db, $d_sql);
  1750. if (empty($dev)) {
  1751. return NULL;
  1752. }
  1753. return $dev["id"];
  1754. }
  1755. function get_device_name($db, $device_id)
  1756. {
  1757. $d_sql = "SELECT device_name FROM devices WHERE id='$device_id'";
  1758. $dev = get_record_sql($db, $d_sql);
  1759. if (empty($dev)) {
  1760. return NULL;
  1761. }
  1762. return $dev["device_name"];
  1763. }
  1764. function get_auth_by_ip($db, $ip)
  1765. {
  1766. $d_sql = "SELECT id FROM user_auth WHERE ip='$ip' and deleted=0";
  1767. $auth = get_record_sql($db, $d_sql);
  1768. if (empty($auth)) {
  1769. return NULL;
  1770. }
  1771. return $auth["id"];
  1772. }
  1773. function get_user_by_ip($db, $ip)
  1774. {
  1775. $d_sql = "SELECT user_id FROM user_auth WHERE ip='$ip' and deleted=0";
  1776. $auth = get_record_sql($db, $d_sql);
  1777. if (empty($auth)) {
  1778. return NULL;
  1779. }
  1780. return $auth["user_id"];
  1781. }
  1782. function get_device_by_auth($db, $id)
  1783. {
  1784. $d_sql = "SELECT id FROM devices WHERE user_id=$id and deleted=0";
  1785. $f_dev = get_record_sql($db, $d_sql);
  1786. if (empty($f_dev)) {
  1787. return NULL;
  1788. }
  1789. return $f_dev['id'];
  1790. }
  1791. function print_auth_port($db, $port_id, $new_window = FALSE)
  1792. {
  1793. $d_sql = "SELECT A.ip, A.ip_int, A.mac, A.id, A.dns_name, A.user_id FROM user_auth as A, connections as C WHERE C.port_id=$port_id and A.id=C.auth_id and A.deleted=0 ORDER BY A.ip_int";
  1794. $t_auth = get_records_sql($db, $d_sql);
  1795. foreach ($t_auth as $row) {
  1796. $name = $row['ip'];
  1797. if (!empty($row['dns_name'])) {
  1798. $name = $row['dns_name'];
  1799. }
  1800. $title = get_login($db, $row['user_id']) . " =>" . $row['ip'] . "[" . $row['mac'] . "]";
  1801. if (!empty($row['dns_name'])) {
  1802. $title .= " | " . $row['dns_name'];
  1803. }
  1804. if ($new_window) {
  1805. print "<a href=\"\" title=\"" . $title . "\" onclick=\"" . open_window_url("/admin/users/editauth.php?id=" . $row['id']) . " return false;\">" . $name . " [" . $row['ip'] . "]</a><br>";
  1806. } else {
  1807. print "<a href=/admin/users/editauth.php?id=" . $row['id'] . " title=\"" . $title . "\" >" . $name . " [" . $row['ip'] . "]</a><br>";
  1808. }
  1809. }
  1810. }
  1811. function get_port_description($db, $port_id, $port_description = '')
  1812. {
  1813. $d_sql = "SELECT A.ip_int, A.description FROM user_auth as A, connections as C WHERE C.port_id=$port_id and A.id=C.auth_id and A.deleted=0 ORDER BY A.ip_int";
  1814. $t_auth = get_records_sql($db, $d_sql);
  1815. $description_found = 0;
  1816. $result = '';
  1817. foreach ($t_auth as $row) {
  1818. if (!empty($row['description'])) {
  1819. $description_found = 1;
  1820. } else {
  1821. $row['description'] = '';
  1822. }
  1823. $result .= $row['description'] . '<br>';
  1824. }
  1825. if (!$description_found) {
  1826. return $port_description;
  1827. }
  1828. if (!empty($port_description)) {
  1829. $result .= '(' . $port_description . ')';
  1830. }
  1831. return $result;
  1832. }
  1833. function print_auth_simple($db, $auth_id)
  1834. {
  1835. $auth = get_record($db, "user_auth", "id=$auth_id");
  1836. $name = $auth['dns_name'];
  1837. if (empty($name)) {
  1838. $name = $auth['description'];
  1839. }
  1840. if (empty($name)) {
  1841. $name = $auth['ip'];
  1842. }
  1843. print "<a href=\"/admin/users/editauth.php?id=$auth_id\">" . $name . "</a><br>";
  1844. }
  1845. function print_auth($db, $auth_id)
  1846. {
  1847. $auth = get_record($db, "user_auth", "id=$auth_id");
  1848. $name = $auth['dns_name'];
  1849. if (empty($name)) {
  1850. $name = $auth['description'];
  1851. } else {
  1852. $name .= " (" . $auth['description'] . ")";
  1853. }
  1854. if (empty($name)) {
  1855. $name = $auth['ip'];
  1856. } else {
  1857. $name .= " [" . $auth['ip'] . "]";
  1858. }
  1859. print "<a href=\"/admin/users/editauth.php?id=$auth_id\">" . $name . "</a><br>";
  1860. }
  1861. function print_auth_detail($db, $auth_id)
  1862. {
  1863. $auth = get_record($db, "user_auth", "id=$auth_id");
  1864. $name = $auth['dns_name'];
  1865. if (empty($name)) {
  1866. $name = $auth['description'];
  1867. } else {
  1868. $name .= " (" . $auth['description'] . ")";
  1869. }
  1870. if (empty($name)) {
  1871. $name = $auth['ip'];
  1872. } else {
  1873. $name .= " [" . $auth['ip'] . "]";
  1874. }
  1875. $name .= " last: [" . $auth['last_found'] . "] ";
  1876. if ($auth['deleted'] == 1) {
  1877. $name .= " <font color='red'>DELETED!!!</font>";
  1878. }
  1879. print "<a href=\"/admin/users/editauth.php?id=$auth_id\">" . $name . "</a><br>";
  1880. }
  1881. function get_auth_port_count($db, $port_id)
  1882. {
  1883. $d_sql = "SELECT count(A.id) as cnt FROM user_auth as A, connections as C WHERE C.port_id=$port_id and A.id=C.auth_id and A.deleted=0";
  1884. $t_device = get_record_sql($db, $d_sql);
  1885. if (empty($t_device)) { return 0; }
  1886. return $t_device['cnt'];
  1887. }
  1888. function get_connection($db, $auth_id)
  1889. {
  1890. $d_sql = "SELECT D.device_name, DP.port FROM devices AS D, device_ports AS DP, connections AS C WHERE D.deleted=0 and D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id=$auth_id";
  1891. $t_device = get_record_sql($db, $d_sql);
  1892. if (!empty($t_device) and isset($t_device['device_name'])) {
  1893. return expand_device_name($db, $t_device['device_name']) . "[" . $t_device['port'] . "]";
  1894. }
  1895. return '';
  1896. }
  1897. function get_connection_string($db, $auth_id)
  1898. {
  1899. $d_sql = "SELECT D.device_name, DP.port FROM devices AS D, device_ports AS DP, connections AS C WHERE D.deleted=0 and D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id=$auth_id";
  1900. $t_device = get_record_sql($db, $d_sql);
  1901. if (!empty($t_device) and isset($t_device['device_name'])) {
  1902. return $t_device['device_name'] . "[" . $t_device['port'] . "]";
  1903. }
  1904. return '';
  1905. }
  1906. function get_port($db, $port_id)
  1907. {
  1908. $d_sql = "SELECT D.device_name, DP.port FROM devices AS D, device_ports AS DP WHERE D.deleted=0 and D.id = DP.device_id AND DP.id = $port_id";
  1909. $t_device = get_record_sql($db, $d_sql);
  1910. if (!empty($t_device) and isset($t_device['device_name'])) {
  1911. return expand_device_name($db, $t_device['device_name']) . "[" . $t_device['port'] . "]";
  1912. }
  1913. return '';
  1914. }
  1915. function print_option_select($db, $option_name)
  1916. {
  1917. print "<select id=\"$option_name\" name=\"$option_name\">\n";
  1918. $t_option = get_records_sql($db, "SELECT id,option_name FROM config_options WHERE uniq=0 AND draft=0 ORDER BY option_name");
  1919. if (!empty($t_option)) {
  1920. foreach ($t_option as $row) {
  1921. print "<option value=".$row['id'].">".$row['option_name']."</option>";
  1922. }
  1923. }
  1924. $t_option = get_records_sql($db, "SELECT id,option_name FROM config_options WHERE draft=0 AND uniq=1 AND id NOT IN (select option_id FROM config where draft=0) ORDER BY option_name");
  1925. if (!empty($t_option)) {
  1926. foreach ($t_option as $row) {
  1927. print "<option value=".$row['id'].">".$row['option_name']."</option>";
  1928. }
  1929. }
  1930. print "</select>\n";
  1931. }
  1932. function ResolveIP($db, $ip_int)
  1933. {
  1934. $ip_name = "-";
  1935. if (empty($ip_int)) {
  1936. return $ip_name;
  1937. }
  1938. $dns_cache = get_record_sql($db, "SELECT * FROM dns_cache WHERE ip=$ip_int");
  1939. if (empty($dns_cache) or empty($dns_cache['dns'])) {
  1940. $ip_name = gethostbyaddr(long2ip($ip_int));
  1941. if (empty($ip_name) or $ip_name == long2ip($ip_int)) {
  1942. $ip_name = "-";
  1943. }
  1944. run_sql($db, "INSERT INTO dns_cache(dns,ip) VALUES('" . $ip_name . "'," . $ip_int . ")");
  1945. } else {
  1946. $ip_name = $dns_cache['dns'];
  1947. }
  1948. return $ip_name;
  1949. }
  1950. function clean_dns_cache($db)
  1951. {
  1952. $date = time();
  1953. $date = $date - 86400;
  1954. $date_clean = DateTimeImmutable::createFromFormat('U', $date);
  1955. $clean_date = $date_clean->format('Y-m-d H:i:s');
  1956. run_sql($db, "DELETE FROM dns_cache WHERE ts<='" . $clean_date . "'");
  1957. }
  1958. function clean_unreferensed_rules($db)
  1959. {
  1960. run_sql($db, "DELETE FROM auth_rules WHERE user_id NOT IN (SELECT id FROM user_list)");
  1961. }
  1962. function FormatDateStr($format = 'Y-m-d H:i:s', $date_str)
  1963. {
  1964. $date1 = GetDateTimeFromString($date_str);
  1965. $result = $date1->format($format);
  1966. return $result;
  1967. }
  1968. function GetDateTimeFromString($date_str)
  1969. {
  1970. if (!is_a($date_str, 'DateTime')) {
  1971. $t_date_str = urldecode($date_str);
  1972. $t_date_str = preg_replace('/(\'|\")/', '', $t_date_str);
  1973. $t_date_str = preg_replace('/T/', ' ', $t_date_str);
  1974. $date1 = DateTime::createFromFormat('Y-m-d H:i:s', $t_date_str);
  1975. if (!$date1) {
  1976. $date1 = DateTime::createFromFormat('Y.m.d H:i:s', $t_date_str);
  1977. }
  1978. if (!$date1) {
  1979. $date1 = DateTime::createFromFormat('Y/m/d H:i:s', $t_date_str);
  1980. }
  1981. if (!$date1) {
  1982. $date1 = DateTime::createFromFormat('Y-m-d H:i', $t_date_str);
  1983. }
  1984. if (!$date1) {
  1985. $date1 = DateTime::createFromFormat('Y.m.d H:i', $t_date_str);
  1986. }
  1987. if (!$date1) {
  1988. $date1 = DateTime::createFromFormat('Y/m/d H:i', $t_date_str);
  1989. }
  1990. if (!$date1) {
  1991. $date1 = DateTime::createFromFormat('Y-m-d|', $t_date_str);
  1992. }
  1993. if (!$date1) {
  1994. $date1 = DateTime::createFromFormat('Y.m.d|', $t_date_str);
  1995. }
  1996. if (!$date1) {
  1997. $date1 = DateTime::createFromFormat('Y/m/d|', $t_date_str);
  1998. }
  1999. if (!$date1) {
  2000. $date1 = new DateTime;
  2001. $date1->setTime(0, 0, 0, 1);
  2002. }
  2003. } else {
  2004. return $date_str;
  2005. }
  2006. return $date1;
  2007. }
  2008. function GetNowTimeString()
  2009. {
  2010. $now = new DateTimeImmutable('now');
  2011. $result = $now->format('Y-m-d H:i:s');
  2012. return $result;
  2013. }
  2014. function GetNowDayString()
  2015. {
  2016. $now = new DateTimeImmutable('now');
  2017. $result = $now->format('Y-m-d');
  2018. return $result;
  2019. }
  2020. function get_ip_subnet($db, $ip)
  2021. {
  2022. if (empty($ip)) {
  2023. return;
  2024. }
  2025. $ip_aton = ip2long($ip);
  2026. $user_subnet = get_record_sql($db, "SELECT * FROM subnets WHERE hotspot=1 or office=1 and ( $ip_aton >= ip_int_start and $ip_aton <= ip_int_stop)");
  2027. if (empty($user_subnet)) {
  2028. return;
  2029. }
  2030. return $user_subnet;
  2031. }
  2032. function find_mac_in_subnet($db, $ip, $mac)
  2033. {
  2034. if (empty($ip)) {
  2035. return;
  2036. }
  2037. if (empty($mac)) {
  2038. return;
  2039. }
  2040. $ip_subnet = get_ip_subnet($db, $ip);
  2041. if (empty($ip_subnet)) {
  2042. return;
  2043. }
  2044. $t_auth = get_records_sql($db, "SELECT id,mac,user_id FROM user_auth WHERE ip_int>=" . $ip_subnet['ip_int_start'] . " and ip_int<=" . $ip_subnet['ip_int_stop'] . " and mac='" . $mac . "' and deleted=0 ORDER BY id");
  2045. $auth_count = 0;
  2046. $result['count'] = 0;
  2047. $result['users_id'] = [];
  2048. foreach ($t_auth as $row) {
  2049. if (!empty($row['id'])) {
  2050. $auth_count++;
  2051. $result['count'] = $auth_count;
  2052. $result[$auth_count] = $row['id'];
  2053. array_push($result['users_id'], $row['user_id']);
  2054. }
  2055. }
  2056. return $result;
  2057. }
  2058. function apply_auth_rule($db, $auth_record, $user_id)
  2059. {
  2060. if (empty($auth_record)) {
  2061. return;
  2062. }
  2063. if (empty($user_id)) {
  2064. return $auth_record;
  2065. }
  2066. $user_rec = get_record($db, 'user_list', "id=" . $user_id);
  2067. if (empty($user_rec)) {
  2068. return $auth_record;
  2069. }
  2070. //set filter and status by user
  2071. $auth_record['ou_id'] = $user_rec['ou_id'];
  2072. $auth_record['user_id'] = $user_rec['id'];
  2073. $auth_record['filter_group_id'] = $user_rec['filter_group_id'];
  2074. $auth_record['queue_id'] = $user_rec['queue_id'];
  2075. $auth_record['enabled'] = $user_rec['enabled'];
  2076. $auth_record['changed'] = 1;
  2077. //maybe fill description?
  2078. if (!empty($user_rec['fio']) and empty($auth_record['description'])) {
  2079. $auth_record['description'] = $user_rec['fio'];
  2080. }
  2081. return $auth_record;
  2082. }
  2083. function fix_auth_rules($db)
  2084. {
  2085. //cleanup hotspot subnet rules
  2086. $t_hotspot = get_records_sql($db, "SELECT * FROM ou WHERE default_users=1 or default_hotspot=1");
  2087. if (!empty($t_hotspot)) {
  2088. foreach ($t_hotspot as $row) {
  2089. delete_record($db, "auth_rules", "ou_id='" . $row['id'] . "'");
  2090. }
  2091. }
  2092. $t_hotspot = get_records_sql($db, "SELECT * FROM subnets WHERE hotspot=1");
  2093. if (!empty($t_hotspot)) {
  2094. foreach ($t_hotspot as $row) {
  2095. delete_record($db, "auth_rules", "rule='" . $row['subnet'] . "'");
  2096. }
  2097. }
  2098. }
  2099. #---------------------------------------------------------------------------------------------------------------
  2100. function new_user($db, $user_info)
  2101. {
  2102. if (!empty($user_info['mac'])) {
  2103. $user['login'] = mac_dotted($user_info['mac']);
  2104. } else {
  2105. $user['login'] = $user_info['ip'];
  2106. }
  2107. if (!empty($user_info['dhcp_hostname'])) {
  2108. $user['fio'] = $user_info['ip'] . '[' . $user_info['dhcp_hostname'] . ']';
  2109. } else {
  2110. $user['fio'] = $user_info['ip'];
  2111. }
  2112. $login_count = get_count_records($db, "user_list", "(login LIKE '" . $user['login'] . "(%)') OR (login='" . $user['login'] . "')");
  2113. if (!empty($login_count) and $login_count > 0) {
  2114. $login_count++;
  2115. $user['login'] = $user['login'] . "(" . $login_count . ")";
  2116. }
  2117. $user['ou_id'] = $user_info['ou_id'];
  2118. $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id=" . $user_info['ou_id']);
  2119. if (!empty($ou_info)) {
  2120. $user['enabled'] = $ou_info['enabled'];
  2121. if (empty($user['enabled'])) {
  2122. $user['enabled'] = 0;
  2123. }
  2124. $user['queue_id'] = $ou_info['queue_id'];
  2125. if (empty($user['queue_id'])) {
  2126. $user['queue_id'] = 0;
  2127. }
  2128. $user['filter_group_id'] = $ou_info['filter_group_id'];
  2129. if (empty($user['filter_group_id'])) {
  2130. $user['filter_group_id'] = 0;
  2131. }
  2132. }
  2133. $result = insert_record($db, "user_list", $user);
  2134. $auto_mac_rule = get_option($db, 64);
  2135. if (!empty($result) and $auto_mac_rule and $user_info['mac']) {
  2136. $auth_rule['user_id'] = $result;
  2137. $auth_rule['type'] = 2;
  2138. $auth_rule['rule'] = mac_dotted($user_info['mac']);
  2139. insert_record($db, "auth_rules", $auth_rule);
  2140. }
  2141. return $result;
  2142. }
  2143. function new_auth($db, $ip, $mac, $user_id)
  2144. {
  2145. $ip_aton = ip2long($ip);
  2146. $msg = '';
  2147. if (!empty($mac)) {
  2148. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE ip_int=$ip_aton AND mac='" . mac_dotted($mac) . "' AND deleted=0");
  2149. if (!empty($auth_record)) {
  2150. LOG_WARNING($db, "Pair ip-mac already exists! Skip creating $ip [$mac] auth_id: " . $auth_record["id"]);
  2151. return $auth_record['id'];
  2152. }
  2153. }
  2154. // save traffic detailization
  2155. $save_traf = get_option($db, 23);
  2156. $resurrection_id = NULL;
  2157. // seek old auth with same ip and mac
  2158. $resurrection_id = get_id_record($db, 'user_auth', " deleted=1 AND ip_int=" . $ip_aton . " AND mac='" . $mac . "'");
  2159. if (!empty($resurrection_id)) {
  2160. $msg .= "Recovered auth_id: $resurrection_id with ip: $ip and mac: $mac ";
  2161. $auth['user_id'] = $user_id;
  2162. $auth['deleted'] = 0;
  2163. $auth['save_traf'] = $save_traf * 1;
  2164. update_record($db, "user_auth", "id=$resurrection_id", $auth);
  2165. } else {
  2166. // not found ->create new record
  2167. $msg .= "Create new ip record \r\nip: $ip\r\nmac: $mac\r\n";
  2168. $auth['deleted'] = 0;
  2169. $auth['user_id'] = $user_id;
  2170. $auth['ip'] = $ip;
  2171. $auth['ip_int'] = $ip_aton;
  2172. if (!empty($mac)) { $auth['mac'] = $mac; }
  2173. $auth['save_traf'] = $save_traf * 1;
  2174. $resurrection_id = insert_record($db, "user_auth", $auth);
  2175. }
  2176. //check rules, update filter and state for new record
  2177. if (!empty($resurrection_id)) {
  2178. $auth = apply_auth_rule($db, $auth, $user_id);
  2179. update_record($db, "user_auth", "id=$resurrection_id", $auth);
  2180. if (!is_hotspot($db, $ip) and !empty($msg)) {
  2181. LOG_WARNING($db, $msg);
  2182. }
  2183. if (is_hotspot($db, $ip) and !empty($msg)) {
  2184. LOG_INFO($db, $msg);
  2185. }
  2186. }
  2187. return $resurrection_id;
  2188. }
  2189. function resurrection_auth($db, $ip_record)
  2190. {
  2191. $ip = $ip_record['ip'];
  2192. $mac = $ip_record['mac'];
  2193. $action = $ip_record['type'];
  2194. $dhcp_hostname = $ip_record['hostname'];
  2195. $hotspot_found = $ip_record['hotspot'];
  2196. $ip_aton = ip2long($ip);
  2197. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE ip_int=$ip_aton AND mac='" . $mac . "' AND deleted=0");
  2198. if (!empty($auth_record)) {
  2199. $user_info = get_record_sql($db, "SELECT * FROM user_list WHERE id=" . $auth_record['user_id']);
  2200. LOG_DEBUG($db, "external dhcp user " . $user_info['login'] . " [" . $ip . "] auth_id: " . $auth_record['id']);
  2201. if (isset($dhcp_hostname) and !empty($dhcp_hostname)) {
  2202. $auth['dhcp_hostname'] = $dhcp_hostname;
  2203. }
  2204. $auth['dhcp_action'] = $action;
  2205. $auth['dhcp_time'] = GetNowTimeString();
  2206. if ($action === 'add') {
  2207. $auth['last_found'] = GetNowTimeString();
  2208. }
  2209. update_record($db, "user_auth", "id=" . $auth_record['id'], $auth);
  2210. return $auth_record['id'];
  2211. }
  2212. $ip_subnet = get_ip_subnet($db, $ip);
  2213. if ($ip_subnet['static']) {
  2214. LOG_WARNING($db, "Unknown pair ip+mac in static subnet! ip: $ip mac: [" . mac_dotted($mac) . "]. Skip");
  2215. return;
  2216. }
  2217. $msg = '';
  2218. // search changed mac
  2219. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE ip_int=$ip_aton AND deleted=0");
  2220. if (!empty($auth_record)) {
  2221. if (empty($auth_record['mac'])) {
  2222. $auth['mac'] = mac_dotted($mac);
  2223. $auth['dhcp_action'] = $action;
  2224. $auth['dhcp_time'] = GetNowTimeString();
  2225. if (!empty($dhcp_hostname)) {
  2226. $auth['dhcp_hostname'] = $dhcp_hostname;
  2227. }
  2228. if ($action === 'add') {
  2229. $auth['last_found'] = GetNowTimeString();
  2230. }
  2231. LOG_INFO($db, "for ip: $ip mac not found! Use empty record...");
  2232. update_record($db, "user_auth", "id=" . $auth_record['id'], $auth);
  2233. return $auth_record['id'];
  2234. } else {
  2235. if (!$hotspot_found) {
  2236. LOG_WARNING($db, "for ip: $ip mac change detected! Old mac: [" . $auth_record['mac'] . "] New mac: [" . mac_dotted($mac) . "]. Disable old auth_id: " . $auth_record['id']);
  2237. }
  2238. run_sql($db, "UPDATE user_auth SET changed=1, deleted=1 WHERE id=" . $auth_record['id']);
  2239. }
  2240. }
  2241. // default id
  2242. $new_user_info = get_new_user_id($db, $ip, $mac, $dhcp_hostname);
  2243. if (!empty($new_user_info['user_id'])) {
  2244. $new_user_id = $new_user_info['user_id'];
  2245. }
  2246. if (empty($new_user_id)) {
  2247. $new_user_id = new_user($db, $new_user_info);
  2248. }
  2249. $resurrection_id = NULL;
  2250. $save_traf = get_option($db, 23);
  2251. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE ip_int=" . $ip_aton . " and mac='" . $mac . "'");
  2252. // seek old auth with same ip and mac
  2253. if (!empty($auth_record)) {
  2254. // found ->Resurrection old record
  2255. $resurrection_id = $auth_record['id'];
  2256. $msg .= "Recovered auth_id: $resurrection_id with ip: $ip and mac: $mac ";
  2257. $auth['dhcp_action'] = $action;
  2258. $auth['user_id'] = $new_user_id;
  2259. $auth['deleted'] = 0;
  2260. $auth['dhcp_time'] = GetNowTimeString();
  2261. $auth['save_traf'] = $save_traf * 1;
  2262. if (!empty($dhcp_hostname)) {
  2263. $auth['dhcp_hostname'] = $dhcp_hostname;
  2264. }
  2265. if ($action === 'add') {
  2266. $auth['last_found'] = GetNowTimeString();
  2267. }
  2268. update_record($db, "user_auth", "id=$resurrection_id", $auth);
  2269. } else {
  2270. // not found ->create new record
  2271. $msg .= "Создаём новый ip-адрес \r\nip: $ip\r\nmac: $mac\r\n";
  2272. $auth['deleted'] = 0;
  2273. $auth['user_id'] = $new_user_id;
  2274. $auth['ip'] = $ip;
  2275. $auth['ip_int'] = $ip_aton;
  2276. $auth['mac'] = $mac;
  2277. $auth['dhcp_action'] = $action;
  2278. $auth['dhcp_time'] = GetNowTimeString();
  2279. $auth['save_traf'] = $save_traf * 1;
  2280. if (!empty($dhcp_hostname)) {
  2281. $auth['dhcp_hostname'] = $dhcp_hostname;
  2282. }
  2283. if ($action == 'add') {
  2284. $auth['last_found'] = GetNowTimeString();
  2285. }
  2286. $resurrection_id = insert_record($db, "user_auth", $auth);
  2287. }
  2288. //check rules, update filter and state for new record
  2289. if (!empty($resurrection_id)) {
  2290. $auth = apply_auth_rule($db, $auth, $new_user_id);
  2291. update_record($db, "user_auth", "id=$resurrection_id", $auth);
  2292. $msg .= "filter: " . $auth['filter_group_id'] . "\r\n queue_id: " . $auth['queue_id'] . "\r\n enabled: " . $auth['enabled'] . "\r\nid: $resurrection_id";
  2293. if (!$hotspot_found and !empty($msg)) {
  2294. LOG_WARNING($db, $msg);
  2295. }
  2296. if ($hotspot_found and !empty($msg)) {
  2297. LOG_INFO($db, $msg);
  2298. }
  2299. }
  2300. return $resurrection_id;
  2301. }
  2302. function get_auth($db, $current_auth)
  2303. {
  2304. if (!isset($current_auth)) {
  2305. return;
  2306. }
  2307. if ($current_auth == 0) {
  2308. return;
  2309. }
  2310. $t_login = get_record_sql($db, "SELECT U.login,A.ip FROM user_list as U, user_auth as A WHERE A.user_id=U.id and A.id=$current_auth");
  2311. if (!empty($t_login) and isset($t_login['login'])) {
  2312. return $f_login['login'] . "[" . $t_login['ip'] . "]";
  2313. }
  2314. return '';
  2315. }
  2316. function get_auth_by_mac($db, $mac)
  2317. {
  2318. if (!isset($mac)) {
  2319. return;
  2320. }
  2321. $mac = mac_dotted($mac);
  2322. $t_login = get_record_sql($db, "SELECT U.id,U.login,A.id as auth_id,A.ip FROM user_list as U, user_auth as A WHERE A.user_id=U.id and A.mac='" . $mac . "' and A.deleted=0 ORDER BY A.last_found DESC");
  2323. if (!empty($t_login) and isset($t_login['id'])) {
  2324. $result['auth'] = '<a href=/admin/users/edituser.php?id=' . $t_login['id'] . '>' . $t_login['login'] . '</a> / ip: <a href=/admin/users/editauth.php?id=' . $t_login['auth_id'] . '>' . $t_login['ip'] . '</a>';
  2325. } else {
  2326. $result['auth'] = 'Unknown';
  2327. }
  2328. $result['mac'] = expand_mac($db, $mac);
  2329. return $result;
  2330. }
  2331. function get_auth_mac($db, $current_auth)
  2332. {
  2333. if (!isset($current_auth)) {
  2334. return;
  2335. }
  2336. if ($current_auth == 0) {
  2337. return;
  2338. }
  2339. $t_login = get_record_sql($db, "SELECT U.login,A.mac FROM user_list as U, user_auth as A WHERE A.user_id=U.id and A.id=$current_auth");
  2340. if (!empty($t_login) and isset($t_loing['login'])) {
  2341. return $t_login['login'] . " [" . $t_login['mac'] . "]";
  2342. }
  2343. return '';
  2344. }
  2345. function add_auth_rule($db, $rule, $type, $user_id)
  2346. {
  2347. $new['user_id'] = $user_id;
  2348. $new['type'] = $type;
  2349. $new['rule'] = $rule;
  2350. $rule_id = 0;
  2351. $auth_rules = get_record_sql($db, "SELECT * FROM auth_rules WHERE rule='" . $rule . "' AND type=" . $type);
  2352. if (empty($auth_rules)) {
  2353. $rule_id = insert_record($db, "auth_rules", $new);
  2354. LOG_INFO($db, "Create auto rule for user_id: " . $user_id . " rule: " . $rule . " type: " . $type);
  2355. } else {
  2356. if ($auth_rules['user_id'] !== $user_id) {
  2357. LOG_WARNING($db, "Create auto rule for user_id: " . $user_id . " rule: " . $rule . " type: " . $type . " failed! Already exists at user_id: " . $auth_rules['user_id']);
  2358. $rule_id = 0;
  2359. } else { $rule_id = $auth_rules['id']; }
  2360. }
  2361. return $rule_id;
  2362. }
  2363. function update_auth_rule($db, $new, $rule_id = 0)
  2364. {
  2365. $type = $new['type'];
  2366. $rule = $new['rule'];
  2367. $auth_rules = get_record_sql($db, "SELECT * FROM auth_rules WHERE rule='" . $rule . "' AND type=" . $type . " AND id<>" . $rule_id);
  2368. if (empty($auth_rules)) {
  2369. $rule_id = update_record($db, "auth_rules", "id=" . $rule_id, $new);
  2370. } else {
  2371. LOG_WARNING($db, "Create auto rule id: " . $rule_id . " rule: " . $rule . " type: " . $type . " failed! Already exists at user_id: " . $auth_rules['user_id']);
  2372. $rule_id = 0;
  2373. }
  2374. return $rule_id;
  2375. }
  2376. function LOG_INFO($db, $msg, $auth_id = 0)
  2377. {
  2378. if (get_const('log_level') < L_INFO) {
  2379. return;
  2380. }
  2381. write_log($db, $msg, L_INFO, $auth_id);
  2382. }
  2383. function LOG_ERROR($db, $msg, $auth_id = 0)
  2384. {
  2385. if (get_const('log_level') < L_ERROR) {
  2386. return;
  2387. }
  2388. email(L_ERROR,$msg);
  2389. write_log($db, $msg, L_ERROR, $auth_id);
  2390. }
  2391. function LOG_VERBOSE($db, $msg, $auth_id = 0)
  2392. {
  2393. if (get_const('log_level') < L_VERBOSE) {
  2394. return;
  2395. }
  2396. write_log($db, $msg, L_VERBOSE, $auth_id);
  2397. }
  2398. function LOG_WARNING($db, $msg, $auth_id = 0)
  2399. {
  2400. if (get_const('log_level') < L_WARNING) {
  2401. return;
  2402. }
  2403. write_log($db, $msg, L_WARNING, $auth_id);
  2404. }
  2405. function LOG_DEBUG($db, $msg, $auth_id = 0)
  2406. {
  2407. if (!empty(get_const('debug')) and get_const('debug')) {
  2408. write_log($db, $msg, L_DEBUG, $auth_id);
  2409. }
  2410. }
  2411. function truncateByWords($string, $length = 100)
  2412. {
  2413. if (strlen($string) <= $length) {
  2414. return $string;
  2415. }
  2416. $wrapped = wordwrap($string, $length);
  2417. $shortened = substr($wrapped, 0, strpos($wrapped, "\n"));
  2418. return $shortened;
  2419. }
  2420. function get_first_line($msg)
  2421. {
  2422. if (empty($msg)) {
  2423. return;
  2424. }
  2425. preg_match('/(.*)(\n|\<br\>)/', $msg, $matches);
  2426. if (!empty($matches[1])) {
  2427. return $matches[1];
  2428. }
  2429. return truncateByWords($msg, 80);
  2430. }
  2431. function email($level = L_WARNING, $msg = '') {
  2432. if (empty($msg)) { return; }
  2433. // Безопасное получение данных сессии
  2434. $currentIp = filter_var($_SESSION['ip'] ?? '127.0.0.1', FILTER_VALIDATE_IP) ?: '127.0.0.1';
  2435. $currentLogin = htmlspecialchars($_SESSION['login'] ?? 'http', ENT_QUOTES, 'UTF-8');
  2436. // Обработка сообщения
  2437. $subjectPrefix = ($level === L_WARNING) ? "WARN: " : "ERROR: ";
  2438. $subject = $subjectPrefix . htmlspecialchars(get_first_line($msg), ENT_QUOTES, 'UTF-8') . "...";
  2439. $messageType = ($level === L_WARNING) ? 'WARNING' : 'ERROR';
  2440. // Формирование HTML-сообщения с экранированием
  2441. $safeMsg = nl2br(htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'));
  2442. $htmlMessage = "<html>
  2443. <body>
  2444. <h1>$messageType!</h1>
  2445. <p>Manager: $currentLogin</p>
  2446. <p>From: $currentIp</p>
  2447. <div>$safeMsg</div>
  2448. </body>
  2449. </html>";
  2450. // Заголовки письма
  2451. $senderEmail = filter_var(get_const('sender_email'), FILTER_VALIDATE_EMAIL);
  2452. if (!$senderEmail) {
  2453. error_log("Invalid sender email address");
  2454. return;
  2455. }
  2456. $boundary = md5(uniqid(time(), true));
  2457. $headers = [
  2458. 'From' => $senderEmail,
  2459. 'Reply-To' => $senderEmail,
  2460. 'X-Mailer' => 'PHP',
  2461. 'MIME-Version' => '1.0',
  2462. 'Content-Type' => 'multipart/mixed; boundary=' . $boundary,
  2463. 'Content-Transfer-Encoding' => 'base64'
  2464. ];
  2465. // Формирование тела письма
  2466. $message = "--$boundary\r\n" .
  2467. "Content-Type: text/html; charset=UTF-8\r\n" .
  2468. "Content-Transfer-Encoding: base64\r\n\r\n" .
  2469. chunk_split(base64_encode($htmlMessage)) . "\r\n" .
  2470. "--$boundary--";
  2471. // Отправка письма
  2472. $adminEmail = filter_var(get_const('admin_email'), FILTER_VALIDATE_EMAIL);
  2473. $additional_parameters = "-f ".$senderEmail;
  2474. if ($adminEmail) {
  2475. if (!mail($adminEmail, $subject, $message, $headers, $additional_parameters)) {
  2476. error_log("Failed to send email to $adminEmail");
  2477. }
  2478. } else {
  2479. error_log("Invalid admin email address");
  2480. }
  2481. }
  2482. function write_log($db, $msg, $level = L_INFO, $auth_id = 0)
  2483. {
  2484. if (!isset($msg)) { return; }
  2485. // Безопасное получение данных сессии
  2486. $currentIp = filter_var($_SESSION['ip'] ?? '127.0.0.1', FILTER_VALIDATE_IP) ?: '127.0.0.1';
  2487. $currentLogin = htmlspecialchars($_SESSION['login'] ?? 'http', ENT_QUOTES, 'UTF-8');
  2488. // Для уровня L_DEBUG пишем в error_log
  2489. if ($level === L_DEBUG) {
  2490. error_log("DEBUG: " . $msg);
  2491. return;
  2492. }
  2493. try {
  2494. // Используем подготовленный запрос PDO напрямую
  2495. $stmt = $db->prepare("INSERT INTO worklog(customer, message, level, auth_id, ip)
  2496. VALUES (:customer, :message, :level, :auth_id, :ip)");
  2497. $result = $stmt->execute([
  2498. ':customer' => $currentLogin,
  2499. ':message' => $msg,
  2500. ':level' => $level,
  2501. ':auth_id' => $auth_id,
  2502. ':ip' => $currentIp
  2503. ]);
  2504. return $result;
  2505. } catch (PDOException $e) {
  2506. // В случае ошибки логируем в error_log, чтобы избежать рекурсии
  2507. error_log("Error writing log to database: " . $e->getMessage());
  2508. return false;
  2509. }
  2510. }
  2511. function print_year_select($year_name, $year)
  2512. {
  2513. print "<select id=\"$year_name\" name=\"$year_name\" >\n";
  2514. for ($i = $year - 10; $i <= $year + 10; $i++) {
  2515. print_select_item($i, $i, $year);
  2516. }
  2517. print "</select>\n";
  2518. }
  2519. function print_date_select($dd, $mm, $yy)
  2520. {
  2521. if ($dd >= 1) {
  2522. print "<b>День</b>\n";
  2523. print "<select id=\"day\" name=\"day\" >\n";
  2524. for ($i = 1; $i <= 31; $i++) {
  2525. print_select_item($i, $i, $dd);
  2526. }
  2527. print "</select>\n";
  2528. }
  2529. if ($mm >= 1) {
  2530. print "<b>Месяц</b>\n";
  2531. print "<select id=\"month\" name=\"month\" >\n";
  2532. for ($i = 1; $i <= 12; $i++) {
  2533. $tmp_date = DateTimeImmutable::createFromFormat('U', strtotime("$i/01/$yy"));
  2534. $month_name = $tmp_date->format('F');
  2535. print_select_item($month_name, $i, $mm);
  2536. }
  2537. print "</select>\n";
  2538. }
  2539. print "<b>Год</b>\n";
  2540. print_year_select('year', $yy);
  2541. }
  2542. function print_date_select2($dd, $mm, $yy)
  2543. {
  2544. if ($dd >= 1) {
  2545. print "<b>День</b>\n";
  2546. print "<select id=\"day2\" name=\"day2\" >\n";
  2547. for ($i = 1; $i <= 31; $i++) {
  2548. print_select_item($i, $i, $dd);
  2549. }
  2550. print "</select>\n";
  2551. }
  2552. if ($mm >= 1) {
  2553. print "<b>Месяц</b>\n";
  2554. print "<select id=\"month2\" name=\"month2\" >\n";
  2555. for ($i = 1; $i <= 12; $i++) {
  2556. $tmp_date = DateTimeImmutable::createFromFormat('U', strtotime("$i/01/$yy"));
  2557. $month_name = $tmp_date->format('F');
  2558. print_select_item($month_name, $i, $mm);
  2559. }
  2560. print "</select>\n";
  2561. }
  2562. print "<b>Год</b>\n";
  2563. print_year_select('year2', $yy);
  2564. }
  2565. function is_up($ip)
  2566. {
  2567. if (!isset($ip) or strlen($ip) == 0) {
  2568. return false;
  2569. }
  2570. exec(sprintf('ping -i .3 -c 1 -W 5 %s', escapeshellarg($ip)), $res, $rval);
  2571. return $rval == 0;
  2572. }
  2573. function apply_device_lock($db, $device_id, $iteration = 0)
  2574. {
  2575. $iteration++;
  2576. if ($iteration > 2) {
  2577. return false;
  2578. }
  2579. // Извлекаем исходную временную метку (без UNIX_TIMESTAMP)
  2580. $dev = get_record_sql($db, 'SELECT discovery_locked, locked_timestamp FROM devices WHERE id = ? AND discovery_locked > 0', [$device_id]);
  2581. // Проверяем, есть ли запись и валидна ли временная метка
  2582. if (empty($dev) || empty($dev['locked_timestamp']) || $dev['locked_timestamp'] === '0000-00-00 00:00:00') {
  2583. LOG_DEBUG($db, "Snmp discovery lock not found. Set and discovery.");
  2584. return set_lock_discovery($db, $device_id);
  2585. }
  2586. // Преобразуем строку даты в Unix timestamp
  2587. try {
  2588. // Удаляем микросекунды (если есть, как в PostgreSQL)
  2589. $ts_str = preg_replace('/\.\d+$/', '', $dev['locked_timestamp']);
  2590. $dt = new DateTime($ts_str);
  2591. $u_locked_timestamp = $dt->getTimestamp();
  2592. } catch (Exception $e) {
  2593. // Если парсинг не удался — считаем блокировку недействительной
  2594. LOG_DEBUG($db, "Invalid lock timestamp format. Resetting lock.");
  2595. return set_lock_discovery($db, $device_id);
  2596. }
  2597. $now = time();
  2598. $wait_time = ($u_locked_timestamp + SNMP_LOCK_TIMEOUT) - $now;
  2599. LOG_DEBUG($db, "Check snmp lock for device id: " . $device_id . ". Lock timestamp: " . $u_locked_timestamp . ", now: " . $now);
  2600. if ($wait_time <= 0) {
  2601. LOG_DEBUG($db, "The lock is already expired. Set new lock.");
  2602. return set_lock_discovery($db, $device_id);
  2603. }
  2604. LOG_VERBOSE($db, "Snmp discovery lock for device id: $device_id found! Need wait " . $wait_time . " sec.");
  2605. sleep($wait_time);
  2606. LOG_VERBOSE($db, "Try set new lock and continue discovery for device id: " . $device_id);
  2607. return apply_device_lock($db, $device_id, $iteration);
  2608. }
  2609. function set_lock_discovery($db, $device_id)
  2610. {
  2611. $new['discovery_locked'] = 1;
  2612. $new['locked_timestamp'] = GetNowTimeString();
  2613. if (update_record($db, 'devices', 'id=' . $device_id, $new)) {
  2614. return true;
  2615. }
  2616. return false;
  2617. }
  2618. function unset_lock_discovery($db, $device_id)
  2619. {
  2620. $new['discovery_locked'] = 0;
  2621. $new['locked_timestamp'] = GetNowTimeString();
  2622. if (update_record($db, 'devices', 'id=' . $device_id, $new)) {
  2623. return true;
  2624. }
  2625. return false;
  2626. }
  2627. function set_port_for_group($db, $group_id, $place_id, $state)
  2628. {
  2629. $authSQL = 'SELECT user_auth.id, user_auth.dns_name, user_auth.ip
  2630. FROM user_auth, user_list
  2631. WHERE user_auth.user_id = user_list.id
  2632. AND user_auth.deleted = 0
  2633. AND user_list.ou_id = ' . $group_id;
  2634. $auth_list = get_records_sql($db, $authSQL);
  2635. LOG_VERBOSE($db, 'Mass port state change started!');
  2636. // Обработка списка авторизаций
  2637. foreach ($auth_list as $row) {
  2638. // Фильтр по месту
  2639. if ($place_id == 0) {
  2640. $place_filter = '';
  2641. } else {
  2642. $place_filter = 'D.building_id = ' . $place_id . ' AND ';
  2643. }
  2644. // Получение информации об устройстве
  2645. $devSQL = 'SELECT D.id, D.device_name, D.vendor_id, D.device_model, D.ip,
  2646. DP.port, DP.snmp_index
  2647. FROM devices AS D, device_ports AS DP, connections AS C
  2648. WHERE ' . $place_filter . '
  2649. D.id = DP.device_id
  2650. AND DP.id = C.port_id
  2651. AND C.auth_id = ' . $row['id'];
  2652. $dev_info = get_record_sql($db, $devSQL);
  2653. if (empty($dev_info)) {
  2654. continue;
  2655. }
  2656. // Получение устройства
  2657. $device = get_record($db, 'devices', "id = " . (int)$dev_info['id']);
  2658. $snmp = getSnmpAccess($device);
  2659. // Определение режима и обновление nagios_handler
  2660. if ($state == 1) {
  2661. $mode = 'enable';
  2662. $runSQL = "UPDATE user_auth
  2663. SET nagios_handler = 'restart-port'
  2664. WHERE id = " . (int)$row['id'] . "
  2665. AND nagios_handler = 'manual-mode'";
  2666. } else {
  2667. $mode = 'disable';
  2668. $runSQL = "UPDATE user_auth
  2669. SET nagios_handler = 'manual-mode'
  2670. WHERE id = " . (int)$row['id'] . "
  2671. AND nagios_handler = 'restart-port'";
  2672. }
  2673. run_sql($db, $runSQL);
  2674. // Логирование
  2675. LOG_INFO($db, "At device " . $dev_info['device_name'] .
  2676. " [" . $dev_info['ip'] . "] " .
  2677. $mode . " port " . $dev_info['port'] .
  2678. " for auth_id: " . $row['id'] .
  2679. " (" . $row['ip'] . " [" . $row['dns_name'] . "])");
  2680. // Установка состояния порта
  2681. set_port_state($dev_info['vendor_id'], $dev_info['snmp_index'],
  2682. $dev_info['ip'], $snmp, $state);
  2683. // Установка состояния PoE
  2684. set_port_poe_state($dev_info['vendor_id'], $dev_info['port'],
  2685. $dev_info['snmp_index'], $dev_info['ip'],
  2686. $snmp, $state);
  2687. }
  2688. LOG_VERBOSE($db, 'Mass port state change stopped.');
  2689. }
  2690. function get_vendor($db, $mac)
  2691. {
  2692. if (empty($mac)) { return ''; }
  2693. $mac = mac_dotted($mac);
  2694. $mac5 = substr($mac, 0, 14);
  2695. $mac4 = substr($mac, 0, 11);
  2696. $mac3 = substr($mac, 0, 8);
  2697. $vendor = null;
  2698. foreach ([$mac, $mac5, $mac4, $mac3] as $oui) {
  2699. $vendor = get_record_sql($db, 'SELECT companyName, companyAddress FROM mac_vendors WHERE oui = ?', [$oui]);
  2700. if (!empty($vendor)) {
  2701. break;
  2702. }
  2703. }
  2704. $result = '';
  2705. if (!empty($vendor)) {
  2706. $result = $vendor['companyName'];
  2707. if (!empty($vendor['companyAddress'])) {
  2708. $result = $vendor['companyAddress'];
  2709. }
  2710. }
  2711. return $result;
  2712. }
  2713. function strHexToBin($number)
  2714. {
  2715. $result = '';
  2716. for ($i = 0; $i < strlen($number); $i++) {
  2717. $conv = base_convert($number[$i], 16, 2);
  2718. $result .= str_pad($conv, 4, '0', STR_PAD_LEFT);
  2719. }
  2720. return $result;
  2721. }
  2722. function dec_to_hex($mac)
  2723. {
  2724. if (!isset($mac)) {
  2725. return;
  2726. }
  2727. $mac_array = explode('.', $mac);
  2728. for ($i = 0; $i < count($mac_array); $i++) {
  2729. $hex_i = dechex($mac_array[$i]);
  2730. if (strlen($hex_i) == 1) {
  2731. $hex_i = "0" . $hex_i;
  2732. }
  2733. $mac_array[$i] = $hex_i;
  2734. }
  2735. $hex_mac = implode(':', $mac_array);
  2736. return $hex_mac;
  2737. }
  2738. function mac_simplify($mac)
  2739. {
  2740. if (!isset($mac)) {
  2741. return;
  2742. }
  2743. $mac = strtolower(trim($mac));
  2744. $mac = preg_replace('/(\.|:|-)/', '', $mac);
  2745. return $mac;
  2746. }
  2747. function mac_dotted($mac)
  2748. {
  2749. if (!isset($mac)) {
  2750. return;
  2751. }
  2752. $mac = mac_simplify($mac);
  2753. $mac = preg_replace('/(\S{2})(\S{2})?(\S{2})?(\S{2})?(\S{2})?(\S{2})?/', '$1:$2:$3:$4:$5:$6', $mac);
  2754. $mac = preg_replace('/\:+$/', '', $mac, 5);
  2755. return $mac;
  2756. }
  2757. function unbind_ports($db, $device_id)
  2758. {
  2759. $target = get_records_sql($db, "SELECT U.target_port_id,U.id FROM device_ports U WHERE U.device_id=$device_id");
  2760. foreach ($target as $row) {
  2761. run_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE target_port_id=" . $row['id']);
  2762. run_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE id=" . $row['id']);
  2763. }
  2764. }
  2765. function bind_ports($db, $port_id, $target_id)
  2766. {
  2767. // unbind current connection
  2768. $new['target_port_id'] = 0;
  2769. $old_target = get_record_sql($db, "SELECT U.target_port_id FROM device_ports U WHERE U.id=$port_id");
  2770. if (!empty($old_target)) {
  2771. $old_target_id = $old_target['target_port_id'];
  2772. update_record($db, "device_ports", "id='$old_target_id'", $new);
  2773. }
  2774. update_record($db, "device_ports", "id='$port_id'", $new);
  2775. // new link
  2776. if (isset($target_id) and $target_id > 0) {
  2777. $new['target_port_id'] = $target_id;
  2778. update_record($db, "device_ports", "id='$port_id'", $new);
  2779. $new['target_port_id'] = $port_id;
  2780. update_record($db, "device_ports", "id='$target_id'", $new);
  2781. }
  2782. }
  2783. function expand_device_name($db, $name)
  2784. {
  2785. $device_id = get_device_id($db, $name);
  2786. $result = $name;
  2787. if (isset($device_id) and $device_id > 0) {
  2788. $result = '<a href=/admin/devices/editdevice.php?id=' . $device_id . '>' . $name . '</a>';
  2789. }
  2790. return $result;
  2791. }
  2792. function expand_mac($db, $msg)
  2793. {
  2794. if (!isset($msg)) {
  2795. return;
  2796. }
  2797. $mac = mac_dotted($msg);
  2798. $vendor_info = get_vendor($db, $mac);
  2799. if (!empty($vendor_info)) {
  2800. // $result = '<p title="' . $vendor_info . '"><a href=/admin/logs/mac.php?mac=' . $mac . '>' . $mac . '</a></p>';
  2801. $result = '<a href=/admin/logs/mac.php?mac=' . $mac . '><p title="' . $vendor_info . '">'. $mac . '</p></a>';
  2802. } else {
  2803. $result = '<a href=/admin/logs/mac.php?mac=' . $mac . '>' . $mac . '</a>';
  2804. }
  2805. return $result;
  2806. }
  2807. function expand_log_str($db, $msg)
  2808. {
  2809. if (!isset($msg)) {
  2810. return;
  2811. }
  2812. $auth_pattern = '/(auth_id:|auth|auth id:|auth id)\s+(\d+)\s+/i';
  2813. $auth_replace = '<a href=/admin/users/editauth.php?id=${2}>auth_id:${2}</a> ';
  2814. $result = preg_replace($auth_pattern, $auth_replace, $msg);
  2815. $user_pattern = '/(user_id:|user|user id:|user id)\s+(\d+)\s+/i';
  2816. $user_replace = '<a href=/admin/users/edituser.php?id=${2}>user_id:${2}</a> ';
  2817. $result = preg_replace($user_pattern, $user_replace, $result);
  2818. $mac_pattern = '/\s+\[(\w{12})\]\s+/i';
  2819. preg_match($mac_pattern, $result, $matches);
  2820. if (isset($matches[1])) {
  2821. $mac = $matches[1];
  2822. $mac = mac_dotted($mac);
  2823. // $vendor_info = get_vendor($db,$mac);
  2824. // $mac_replace = ' <p title="'.$vendor_info.'"><a href=/admin/logs/mac.php?mac='.$mac.'>'.$mac.'</a></p>';
  2825. $mac_replace = ' <a href=/admin/logs/mac.php?mac=' . $mac . '>' . $mac . '</a> ';
  2826. $result = preg_replace($mac_pattern, $mac_replace, $result);
  2827. }
  2828. $mac_pattern = '/\s+mac:\s+([\w\:]{17})$/i';
  2829. preg_match($mac_pattern, $result, $matches);
  2830. if (isset($matches[1])) {
  2831. $mac = $matches[1];
  2832. $mac = mac_dotted($mac);
  2833. // $vendor_info = get_vendor($db,$mac);
  2834. // $mac_replace = ' mac: <p title="'.$vendor_info.'"><a href=/admin/logs/mac.php?mac='.$mac.'>'.$mac.'</a></p>';
  2835. $mac_replace = ' mac: <a href=/admin/logs/mac.php?mac=' . $mac . '>' . $mac . '</a> ';
  2836. $result = preg_replace($mac_pattern, $mac_replace, $result);
  2837. }
  2838. $device_pattern = '/at device\s+([\w\.\-]+)/i';
  2839. preg_match($device_pattern, $result, $matches);
  2840. if (isset($matches[1])) {
  2841. $device_name = $matches[1];
  2842. $device_id = get_device_id($db, $device_name);
  2843. if (isset($device_id) and $device_id > 0) {
  2844. $device_replace = 'at device <a href=/admin/devices/editdevice.php?id=' . $device_id . '>${1}</a> ';
  2845. $result = preg_replace($device_pattern, $device_replace, $result);
  2846. }
  2847. }
  2848. $device_pattern = '/(device_id:|device id:|device id|device_id)\s+(\d+)\s+/i';
  2849. $device_replace = 'device_id: <a href=/admin/devices/editdevice.php?id=${2}>${2}</a> ';
  2850. $result = preg_replace($device_pattern, $device_replace, $result);
  2851. $ip_pattern = '/\s+ip\:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+/i';
  2852. preg_match($ip_pattern, $result, $matches);
  2853. if (isset($matches[1])) {
  2854. $ip = $matches[1];
  2855. $auth_id = get_auth_by_ip($db, $ip);
  2856. if (isset($auth_id) and $auth_id > 0) {
  2857. $auth_replace = ' ip: <a href=/admin/users/editauth.php?id=' . $auth_id . '>${1}</a> ';
  2858. $result = preg_replace($ip_pattern, $auth_replace, $result);
  2859. }
  2860. }
  2861. return $result;
  2862. }
  2863. function is_auth_bind_changed($db, $id, $ip, $mac)
  2864. {
  2865. $old_sql = "SELECT ip,mac FROM user_auth WHERE id=$id";
  2866. $old_record = get_record_sql($db, $old_sql);
  2867. if (empty($old_record["ip"]) or empty($old_record["mac"])) {
  2868. return 0;
  2869. }
  2870. if ($old_record["ip"] !== $ip or $old_record["mac"] !== $mac) {
  2871. LOG_VERBOSE($db, "Changed ip or mac for auth record!");
  2872. return 1;
  2873. }
  2874. return 0;
  2875. }
  2876. function copy_auth($db, $id, $new_auth)
  2877. {
  2878. $old_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id=$id");
  2879. delete_record($db, "user_auth", "id=" . $id);
  2880. $new_auth["user_id"] = $old_record["user_id"];
  2881. $new_auth["changed"] = 1;
  2882. $changed_time = GetNowTimeString();
  2883. $new_auth["changed_time"] = $changed_time;
  2884. $new_id = insert_record($db, "user_auth", $new_auth);
  2885. LOG_VERBOSE($db, "Old record with id: $id deleted. Created new auth record for new ip+mac id: $new_id!");
  2886. return $new_id;
  2887. }
  2888. function get_dns_name($db, $id)
  2889. {
  2890. $auth_record = get_record_sql($db, "SELECT dns_name FROM user_auth WHERE id=" . $id);
  2891. if (!empty($auth_record) and !empty($auth_record['dns_name'])) {
  2892. return $auth_record['dns_name'];
  2893. }
  2894. return '';
  2895. }
  2896. function get_cacti_graph($host_ip, $port_index)
  2897. {
  2898. if (empty(get_const('cacti_url'))) {
  2899. return;
  2900. }
  2901. if (CACTI_DB_HOST == null or CACTI_DB_USER == null or CACTI_DB_PASS == null or CACTI_DB_NAME == null) {
  2902. return;
  2903. }
  2904. if (empty(CACTI_DB_HOST) or empty(CACTI_DB_USER) or empty(CACTI_DB_PASS) or empty(CACTI_DB_NAME)) {
  2905. return;
  2906. }
  2907. $cacti_db_link = new_connection('mysql',CACTI_DB_HOST, CACTI_DB_USER, CACTI_DB_PASS, CACTI_DB_NAME);
  2908. if (!$cacti_db_link) {
  2909. return FALSE;
  2910. }
  2911. $host_sql = 'SELECT * FROM host WHERE hostname="' . $host_ip . '"';
  2912. $cacti_host = get_record_sql($cacti_db_link, $host_sql);
  2913. $host_id = $cacti_host["id"];
  2914. if (empty($host_id)) {
  2915. return;
  2916. }
  2917. $graph_sql = 'SELECT * FROM graph_local WHERE host_id="' . $host_id . '" and snmp_index="' . $port_index . '" and graph_template_id IN (SELECT id FROM graph_templates WHERE name LIKE "Interface - Traffic%") ORDER BY id ASC';
  2918. $cacti_graph = get_record_sql($cacti_db_link, $graph_sql);
  2919. $graph_id = $cacti_graph["id"];
  2920. if (empty($graph_id)) {
  2921. return;
  2922. }
  2923. $result = get_const('cacti_url') . "/graph_image.php?local_graph_id=" . $graph_id;
  2924. return $result;
  2925. }
  2926. function print_select_item($description, $value, $current)
  2927. {
  2928. if ((string)$value === (string)$current) {
  2929. print "<option value='" . $value . "' selected>$description</option>";
  2930. } else {
  2931. print "<option value='" . $value . "'>$description</option>";
  2932. }
  2933. }
  2934. function print_select_simple($description, $value)
  2935. {
  2936. print "<option value=$value>$description</option>";
  2937. }
  2938. function print_select_item_ext($description, $value, $current, $disabled)
  2939. {
  2940. if ((string)$value === (string)$current) {
  2941. print "<option value=$value selected>$description</option>";
  2942. } else {
  2943. if (!$disabled) {
  2944. print "<option value=$value>$description</option>";
  2945. } else {
  2946. print "<option disabled value=$value>$description</option>";
  2947. }
  2948. }
  2949. }
  2950. function print_row_at_pages($name, $value)
  2951. {
  2952. print "<select id='" . $name . "' name='" . $name . "'>\n";
  2953. print_select_item(WEB_select_item_more, pow(10, 10), $value);
  2954. print_select_item('25', 25, $value);
  2955. print_select_item('50', 50, $value);
  2956. print_select_item('100', 100, $value);
  2957. print_select_item('200', 200, $value);
  2958. print_select_item('500', 500, $value);
  2959. print_select_item('1000', 1000, $value);
  2960. print_select_item('2000', 2000, $value);
  2961. print "</select>\n";
  2962. }
  2963. function print_navigation($url, $page, $displayed, $count_records, $total)
  2964. {
  2965. if ($total <= 1) {
  2966. print "<div align=left class=records >";
  2967. print "| Total records: $count_records";
  2968. print "</div>";
  2969. return;
  2970. }
  2971. $v_char = "?";
  2972. if (preg_match('/\.php\?/', $url)) {
  2973. $v_char = "&";
  2974. }
  2975. //две назад
  2976. print "<div align=left class=records >";
  2977. if (($page - 2) > 0) :
  2978. $pagetwoleft = "<a class='first_page_link' href=" . $url . $v_char . "page=" . ($page - 2) . ">" . ($page - 2) . "</a> ";
  2979. else :
  2980. $pagetwoleft = null;
  2981. endif;
  2982. //одна назад
  2983. if (($page - 1) > 0) :
  2984. $pageoneleft = "<a class='first_page_link' href=" . $url . $v_char . "page=" . ($page - 1) . ">" . ($page - 1) . "</a> ";
  2985. $pagetemp = ($page - 1);
  2986. else :
  2987. $pageoneleft = null;
  2988. $pagetemp = null;
  2989. endif;
  2990. //две вперед
  2991. if (($page + 2) <= $total) :
  2992. $pagetworight = " <a class='first_page_link' href=" . $url . $v_char . "page=" . ($page + 2) . ">" . ($page + 2) . "</a>";
  2993. else :
  2994. $pagetworight = null;
  2995. endif;
  2996. //одна вперед
  2997. if (($page + 1) <= $total) :
  2998. $pageoneright = " <a class='first_page_link' href=" . $url . $v_char . "page=" . ($page + 1) . ">" . ($page + 1) . "</a>";
  2999. $pagetemp2 = ($page + 1);
  3000. else :
  3001. $pageoneright = null;
  3002. $pagetemp2 = null;
  3003. endif;
  3004. // в начало
  3005. if ($page != 1 && $pagetemp != 1 && $pagetemp != 2) :
  3006. $pagerevp = "<a href=" . $url . $v_char . "page=1 class='first_page_link' title='В начало'><<</a> ";
  3007. else :
  3008. $pagerevp = null;
  3009. endif;
  3010. //в конец (последняя)
  3011. if ($page != $total && $pagetemp2 != ($total - 1) && $pagetemp2 != $total) :
  3012. $nextp = " ... <a href=" . $url . $v_char . "page=" . $total . " class='first_page_link'>$total</a>";
  3013. else :
  3014. $nextp = null;
  3015. endif;
  3016. print $pagerevp . $pagetwoleft . $pageoneleft . '<span class="num_page_not_link"><b>' . $page . '</b></span>' . $pageoneright . $pagetworight . $nextp;
  3017. print " | Total records: $count_records";
  3018. print "</div>";
  3019. }
  3020. function get_option($db, $option_id)
  3021. {
  3022. // Валидация входного параметра
  3023. if (!is_numeric($option_id) || $option_id <= 0) {
  3024. return null;
  3025. }
  3026. $sql = "
  3027. SELECT
  3028. COALESCE(c.value, co.default_value) AS value,
  3029. co.option_type
  3030. FROM config_options co
  3031. LEFT JOIN config c ON c.option_id = co.id
  3032. WHERE co.id = ?
  3033. ";
  3034. $record = get_record_sql($db, $sql, [$option_id]);
  3035. if ($record && isset($record['value'])) {
  3036. return $record['value'];
  3037. }
  3038. return null;
  3039. }
  3040. function is_option($db, $option_id)
  3041. {
  3042. $option = get_record($db, "config", "option_id=" . $option_id);
  3043. if (empty($option) or empty($option['value'])) {
  3044. return;
  3045. }
  3046. return 1;
  3047. }
  3048. function set_option($db, $option_id, $value)
  3049. {
  3050. $option['value'] = $value;
  3051. update_record($db, 'config', "option_id=$option_id", $option);
  3052. }
  3053. function is_subnet_aton($subnet, $ip)
  3054. {
  3055. if (!isset($subnet)) {
  3056. return 0;
  3057. }
  3058. if (!isset($ip)) {
  3059. return 0;
  3060. }
  3061. $range = cidrToRange($subnet);
  3062. if ($ip >= ip2long($range[0]) and $ip <= ip2long($range[1])) {
  3063. return 1;
  3064. }
  3065. return 0;
  3066. }
  3067. function get_new_user_id($db, $ip, $mac, $hostname)
  3068. {
  3069. $result['ip'] = $ip;
  3070. $result['mac'] = mac_dotted($mac);
  3071. $result['hostname'] = $hostname;
  3072. $result['user_id'] = NULL;
  3073. $result['ou_id'] = NULL;
  3074. $ip_aton = ip2long($ip);
  3075. if (is_hotspot($db, $ip)) {
  3076. $result['ou_id'] = get_const('default_hotspot_ou_id');
  3077. return $result;
  3078. }
  3079. //personal user rules
  3080. //ip
  3081. if (!empty($ip)) {
  3082. $t_rules = get_records_sql($db, "SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL");
  3083. foreach ($t_rules as $row) {
  3084. if (!empty($row['rule']) and is_subnet_aton($row['rule'], $ip_aton)) {
  3085. $result['user_id'] = $row['user_id'];
  3086. return $result;
  3087. }
  3088. }
  3089. }
  3090. //mac
  3091. if (!empty($mac)) {
  3092. $mac_rules = get_records_sql($db, "SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL");
  3093. foreach ($mac_rules as $row) {
  3094. $pattern = '/' . mac_simplify($row['rule']) . '/';
  3095. if (!empty($row['rule']) and preg_match($pattern, mac_simplify($mac))) {
  3096. $result['user_id'] = $row['user_id'];
  3097. return $result;
  3098. }
  3099. }
  3100. }
  3101. //hostname
  3102. if (!empty($hostname)) {
  3103. $mac_rules = get_records_sql($db, "SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL");
  3104. foreach ($mac_rules as $row) {
  3105. if (!empty($row['rule']) and preg_match($row['rule'], $hostname)) {
  3106. $result['user_id'] = $row['user_id'];
  3107. return $result;
  3108. }
  3109. }
  3110. }
  3111. //ou rules
  3112. //ip
  3113. if (!empty($ip)) {
  3114. $t_rules = get_records_sql($db, "SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL");
  3115. foreach ($t_rules as $row) {
  3116. if (!empty($row['rule']) and is_subnet_aton($row['rule'], $ip_aton)) {
  3117. $result['ou_id'] = $row['ou_id'];
  3118. return $result;
  3119. }
  3120. }
  3121. }
  3122. //mac
  3123. if (!empty($mac)) {
  3124. $mac_rules = get_records_sql($db, "SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL");
  3125. foreach ($mac_rules as $row) {
  3126. $pattern = '/' . mac_simplify($row['rule']) . '/';
  3127. if (!empty($row['rule']) and preg_match($pattern, mac_simplify($mac))) {
  3128. $result['ou_id'] = $row['ou_id'];
  3129. return $result;
  3130. }
  3131. }
  3132. }
  3133. //hostname
  3134. if (!empty($hostname)) {
  3135. $mac_rules = get_records_sql($db, "SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL");
  3136. foreach ($mac_rules as $row) {
  3137. if (!empty($row['rule']) and preg_match($row['rule'], $hostname)) {
  3138. $result['ou_id'] = $row['ou_id'];
  3139. return $result;
  3140. }
  3141. }
  3142. }
  3143. if (empty($result['ou_id'])) {
  3144. $result['ou_id'] = get_const('default_user_ou_id');
  3145. }
  3146. return $result;
  3147. }
  3148. function get_subnet_range($db, $subnet_id)
  3149. {
  3150. if (empty($subnet_id)) {
  3151. return;
  3152. }
  3153. $t_option = get_record_sql($db, "SELECT ip_int_start,ip_int_stop FROM subnets WHERE id=$subnet_id");
  3154. if (!isset($t_option['ip_int_start'])) {
  3155. $t_option['ip_int_start'] = 0;
  3156. }
  3157. if (!isset($t_option['ip_int_stop'])) {
  3158. $t_option['ip_int_stop'] = 0;
  3159. }
  3160. $subnet['start'] = $t_option['ip_int_start'];
  3161. $subnet['stop'] = $t_option['ip_int_stop'];
  3162. return $subnet;
  3163. }
  3164. function int_between($value, $start, $end)
  3165. {
  3166. return in_array($value, range($start, $end));
  3167. }
  3168. function is_gray_network($ip)
  3169. {
  3170. if (empty($ip)) {
  3171. return 0;
  3172. }
  3173. $ip_aton = ip2long($ip);
  3174. $gray_nets = array('10.0.0.0/8', '192.168.0.0/16', '172.16.0.0/12', '100.64.0.0/10');
  3175. foreach ($gray_nets as &$net) {
  3176. $net_cidr = cidrToRange($net);
  3177. if (int_between($ip_aton, ip2long($net_cidr[0]), ip2long($net_cidr[1]))) {
  3178. return $net;
  3179. }
  3180. }
  3181. return 0;
  3182. }
  3183. function is_hotspot($db, $ip)
  3184. {
  3185. if (!isset($ip)) {
  3186. return 0;
  3187. }
  3188. LOG_DEBUG($db, "Check hotspot network for ip: $ip");
  3189. $ip_aton = ip2long($ip);
  3190. $t_option = get_records_sql($db, "SELECT subnet,ip_int_start,ip_int_stop FROM subnets WHERE hotspot=1");
  3191. foreach ($t_option as $row) {
  3192. if ($ip_aton >= $row['ip_int_start'] and $ip_aton <= $row['ip_int_stop']) {
  3193. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in hotspot network ".$row['subnet'].": [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  3194. return 1;
  3195. }
  3196. }
  3197. LOG_DEBUG($db, "ip $ip not found in hotspot network!");
  3198. return 0;
  3199. }
  3200. function is_office($db, $ip)
  3201. {
  3202. if (!isset($ip)) {
  3203. return 0;
  3204. }
  3205. LOG_DEBUG($db, "Check office network for ip: $ip");
  3206. $ip_aton = ip2long($ip);
  3207. $t_option = get_records_sql($db, "SELECT subnet,ip_int_start,ip_int_stop FROM subnets WHERE office=1");
  3208. foreach ($t_option as $row) {
  3209. if ($ip_aton >= $row['ip_int_start'] and $ip_aton <= $row['ip_int_stop']) {
  3210. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in office network ".$row['subnet'].": [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  3211. return 1;
  3212. }
  3213. }
  3214. LOG_DEBUG($db, "ip $ip not found in office network!");
  3215. return 0;
  3216. }
  3217. function get_office_subnet($db, $ip)
  3218. {
  3219. if (!isset($ip)) {
  3220. return 0;
  3221. }
  3222. LOG_DEBUG($db, "Check office network for ip: $ip");
  3223. $ip_aton = ip2long($ip);
  3224. $subnets = get_records_sql($db, 'SELECT * FROM subnets WHERE office=1');
  3225. foreach ($subnets as $row) {
  3226. if ($ip_aton >= $row['ip_int_start'] and $ip_aton <= $row['ip_int_stop']) {
  3227. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in office {$row['subnet']}: [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  3228. return $row;
  3229. }
  3230. }
  3231. LOG_DEBUG($db, "ip $ip not found in office network!");
  3232. return 0;
  3233. }
  3234. function get_notify_subnet($db, $ip)
  3235. {
  3236. if (!isset($ip)) {
  3237. return 0;
  3238. }
  3239. $office_subnet = get_office_subnet($db, $ip);
  3240. if ($office_subnet) {
  3241. return $office_subnet['notify'];
  3242. }
  3243. return 0;
  3244. }
  3245. function is_our_network($db, $ip)
  3246. {
  3247. if (!isset($ip)) {
  3248. return 0;
  3249. }
  3250. if (is_hotspot($db, $ip)) {
  3251. return 1;
  3252. }
  3253. if (is_office($db, $ip)) {
  3254. return 1;
  3255. }
  3256. return 0;
  3257. }
  3258. function get_const($const_name)
  3259. {
  3260. global $config;
  3261. if (isset($config[$const_name])) {
  3262. return $config[$const_name];
  3263. }
  3264. return NULL;
  3265. }
  3266. function get_eye_version($db)
  3267. {
  3268. $v_table = get_record_sql($db, "SELECT version FROM version");
  3269. if (!empty($v_table)) {
  3270. return $v_table['version'];
  3271. }
  3272. return NULL;
  3273. }
  3274. function getNotifyFlags(): array {
  3275. return [
  3276. WEB_NOTIFY_NONE => NOTIFY_NONE,
  3277. WEB_NOTIFY_CREATE => NOTIFY_CREATE,
  3278. WEB_NOTIFY_UPDATE => NOTIFY_UPDATE,
  3279. WEB_NOTIFY_DELETE => NOTIFY_DELETE,
  3280. ];
  3281. }
  3282. function getNotifyLabels(): array {
  3283. return [
  3284. NOTIFY_NONE => WEB_NOTIFY_NONE,
  3285. NOTIFY_CREATE => WEB_NOTIFY_CREATE,
  3286. NOTIFY_UPDATE => WEB_NOTIFY_UPDATE,
  3287. NOTIFY_DELETE => WEB_NOTIFY_DELETE,
  3288. ];
  3289. }
  3290. function printFlagsByFirstLetter(int $flags): string {
  3291. if ($flags === 0) {
  3292. return 'x';
  3293. }
  3294. $flagLabels = getNotifyLabels();
  3295. $activeLetters = [];
  3296. $fullLabels = [];
  3297. foreach ($flagLabels as $flagValue => $label) {
  3298. if ($flagValue === 0) continue;
  3299. if (($flags & $flagValue) === $flagValue) {
  3300. $firstLetter = mb_substr($label, 0, 1, 'UTF-8');
  3301. $activeLetters[] = $firstLetter;
  3302. $fullLabels[] = $label;
  3303. }
  3304. }
  3305. sort($activeLetters);
  3306. $letters = implode('', $activeLetters);
  3307. $tooltipText = implode(', ', $fullLabels);
  3308. return '<span title="' . htmlspecialchars($tooltipText) . '">' . htmlspecialchars($letters) . '</span>';
  3309. }
  3310. function renderNotifyCombobox(string $name, int $selectedFlags = 0, array $attributes = []): string {
  3311. $labels = getNotifyLabels();
  3312. $flags = getNotifyFlags();
  3313. // Собираем атрибуты
  3314. $attrString = '';
  3315. foreach ($attributes as $key => $value) {
  3316. $attrString .= ' ' . htmlspecialchars($key) . '="' . htmlspecialchars($value) . '"';
  3317. }
  3318. // Предопределенные комбинации с читаемыми названиями
  3319. $combinations = [
  3320. NOTIFY_NONE => $labels[NOTIFY_NONE],
  3321. NOTIFY_CREATE => $labels[NOTIFY_CREATE],
  3322. NOTIFY_UPDATE => $labels[NOTIFY_UPDATE],
  3323. NOTIFY_DELETE => $labels[NOTIFY_DELETE],
  3324. NOTIFY_CREATE | NOTIFY_UPDATE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_UPDATE],
  3325. NOTIFY_CREATE | NOTIFY_DELETE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_DELETE],
  3326. NOTIFY_UPDATE | NOTIFY_DELETE => $labels[NOTIFY_UPDATE] . ' + ' . $labels[NOTIFY_DELETE],
  3327. NOTIFY_CREATE | NOTIFY_UPDATE | NOTIFY_DELETE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_UPDATE] . ' + ' . $labels[NOTIFY_DELETE],
  3328. ];
  3329. $html = '<select name="' . htmlspecialchars($name) . '"' . $attrString . '>';
  3330. foreach ($combinations as $value => $label) {
  3331. $isSelected = ($selectedFlags === $value);
  3332. $selected = $isSelected ? ' selected' : '';
  3333. $html .= '<option value="' . $value . '"' . $selected . '>'
  3334. . htmlspecialchars($label)
  3335. . '</option>';
  3336. }
  3337. $html .= '</select>';
  3338. return $html;
  3339. }
  3340. /**
  3341. * Проверяет, установлен ли флаг создания
  3342. */
  3343. function isNotifyCreate(int $flags): bool {
  3344. return ($flags & NOTIFY_CREATE) === NOTIFY_CREATE;
  3345. }
  3346. /**
  3347. * Проверяет, установлен ли флаг изменения
  3348. */
  3349. function isNotifyUpdate(int $flags): bool {
  3350. return ($flags & NOTIFY_UPDATE) === NOTIFY_UPDATE;
  3351. }
  3352. /**
  3353. * Проверяет, установлен ли флаг удаления
  3354. */
  3355. function isNotifyDelete(int $flags): bool {
  3356. return ($flags & NOTIFY_DELETE) === NOTIFY_DELETE;
  3357. }
  3358. /**
  3359. * Проверяет, отключены ли все уведомления
  3360. */
  3361. function isNotifyNone(int $flags): bool {
  3362. return $flags === NOTIFY_NONE;
  3363. }
  3364. /**
  3365. * Проверяет, установлен ли конкретный флаг
  3366. */
  3367. function hasNotifyFlag(int $flags, int $flagToCheck): bool {
  3368. return ($flags & $flagToCheck) === $flagToCheck;
  3369. }
  3370. /**
  3371. * Устанавливает флаг(и)
  3372. */
  3373. function setNotifyFlag(int &$flags, int $flagToSet): void {
  3374. $flags |= $flagToSet;
  3375. }
  3376. /**
  3377. * Снимает флаг(и)
  3378. */
  3379. function unsetNotifyFlag(int &$flags, int $flagToUnset): void {
  3380. $flags &= ~$flagToUnset;
  3381. }
  3382. /**
  3383. * Преобразует массив выбранных значений в битовую маску
  3384. */
  3385. function arrayToNotifyFlags(array $selectedValues): int {
  3386. $flags = NOTIFY_NONE;
  3387. foreach ($selectedValues as $value) {
  3388. $flags |= (int)$value;
  3389. }
  3390. return $flags;
  3391. }
  3392. /**
  3393. * Проверяет, является ли OU системным (используется по умолчанию для пользователей или хотспотов)
  3394. *
  3395. * @param PDO $db
  3396. * @param int $ou_id
  3397. * @return bool
  3398. */
  3399. function is_system_ou($db, $ou_id = null) {
  3400. if (empty($ou_id) || !is_numeric($ou_id) || $ou_id <= 0) {
  3401. return false;
  3402. }
  3403. $sql = "SELECT 1 FROM ou WHERE id = ? AND (default_users = 1 OR default_hotspot = 1)";
  3404. return !empty(get_record_sql($db, $sql, [$ou_id]));
  3405. }
  3406. $config["org_name"] = get_option($db_link, 32);
  3407. $config["version"] = get_eye_version($db_link);
  3408. $config["KB"] = get_option($db_link, 1);
  3409. if ($config["KB"] == 0) {
  3410. $config["KB"] = 1000;
  3411. }
  3412. if ($config["KB"] == 1) {
  3413. $config["KB"] = 1024;
  3414. }
  3415. $config["debug"] = get_option($db_link, 34);
  3416. $config["log_level"] = get_option($db_link, 53);
  3417. if ($config["debug"]) {
  3418. $config["log_level"] = 255;
  3419. }
  3420. $config["send_email"] = get_option($db_link, 51);
  3421. $config["admin_email"] = get_option($db_link, 21);
  3422. $config["sender_email"] = get_option($db_link, 52);
  3423. $config["snmp_default_version"] = get_option($db_link, 9);
  3424. $config["snmp_default_community"] = get_option($db_link, 11);
  3425. $config["auto_mac_rule"] = get_option($db_link, 64);
  3426. $config["traffic_ipstat_history"] = get_option($db_link, 56);
  3427. $config["cacti_url"] = rtrim(get_option($db_link, 58), '/');
  3428. if (preg_match('/127.0.0.1/', $config["cacti_url"])) {
  3429. $config["cacti_url"] = NULL;
  3430. }
  3431. $config["nagios_url"] = rtrim(get_option($db_link, 57), '/') . '/cgi-bin/';
  3432. if (preg_match('/127.0.0.1/', $config["nagios_url"])) {
  3433. $config["nagios_url"] = NULL;
  3434. }
  3435. $config["torrus_url"] = rtrim(get_option($db_link, 59), '/') . '?nodeid=if//HOST_IP//IF_NAME////inoutbps';
  3436. if (preg_match('/127.0.0.1/', $config["torrus_url"])) {
  3437. $config["torrus_url"] = NULL;
  3438. }
  3439. $config["dns_server"] = get_option($db_link, 3);
  3440. $config["dns_server_type"] = get_option($db_link, 70);
  3441. $ou = get_record_sql($db_link, "SELECT id FROM ou WHERE default_users = 1");
  3442. if (empty($ou)) {
  3443. $config["default_user_ou_id"] = 0;
  3444. } else {
  3445. $config["default_user_ou_id"] = $ou['id'];
  3446. }
  3447. $ou = get_record_sql($db_link, "SELECT id FROM ou WHERE default_hotspot=1");
  3448. if (empty($ou)) {
  3449. $config["default_hotspot_ou_id"] = $config["default_user_ou_id"];
  3450. } else {
  3451. $config["default_hotspot_ou_id"] = $ou['id'];
  3452. }
  3453. $config["init"] = 1;
  3454. clean_dns_cache($db_link);
  3455. //clean_unreferensed_rules($db_link);
  3456. $config["debug"] = 1;