common.php 128 KB

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