common.php 123 KB

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