common.php 125 KB

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