common.php 129 KB

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