common.php 123 KB

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