common.php 127 KB

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