common.php 122 KB

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