common.php 119 KB

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