common.php 125 KB

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