common.php 122 KB

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