api.networking.php 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688
  1. <?php
  2. /**
  3. * Returns IP usage stats for available networks
  4. *
  5. * @return array
  6. */
  7. function multinet_getFreeIpStats() {
  8. $result = array();
  9. $allServices = array();
  10. $allNets = array();
  11. $nethostsUsed = array();
  12. $servicesTmp = multinet_get_services();
  13. $netsTmp = multinet_get_all_networks();
  14. $neth_q = "SELECT COUNT(id) as count, netid from `nethosts` group by `netid`";
  15. $nethTmp = simple_queryall($neth_q);
  16. if (!empty($nethTmp)) {
  17. foreach ($nethTmp as $io => $each) {
  18. $nethostsUsed[$each['netid']] = $each['count'];
  19. }
  20. }
  21. if (!empty($servicesTmp)) {
  22. foreach ($servicesTmp as $io => $each) {
  23. $allServices[$each['netid']]['desc'] = $each['desc'];
  24. $allServices[$each['netid']]['servid'] = $each['id'];
  25. }
  26. }
  27. if (!empty($netsTmp)) {
  28. foreach ($netsTmp as $io => $each) {
  29. $allNets[$each['id']]['desc'] = $each['desc'];
  30. $allNets[$each['id']]['total'] = multinet_totalips_count($each['startip'], $each['endip']);
  31. //finding used hosts count
  32. if (isset($nethostsUsed[$each['id']])) {
  33. $allNets[$each['id']]['used'] = $nethostsUsed[$each['id']];
  34. } else {
  35. $allNets[$each['id']]['used'] = 0;
  36. }
  37. //finding network associated service
  38. if (isset($allServices[$each['id']])) {
  39. $allNets[$each['id']]['service'] = $allServices[$each['id']]['desc'];
  40. $allNets[$each['id']]['serviceid'] = $allServices[$each['id']]['servid'];
  41. } else {
  42. $allNets[$each['id']]['service'] = '';
  43. $allNets[$each['id']]['serviceid'] = '';
  44. }
  45. //free IPs counter
  46. $allNets[$each['id']]['free'] = $allNets[$each['id']]['total'] - $allNets[$each['id']]['used'];
  47. }
  48. }
  49. return ($allNets);
  50. }
  51. /**
  52. * Fast count of possible pool size for some IPs range
  53. *
  54. * @param string $first_ip
  55. * @param string $last_ip
  56. *
  57. * @return int
  58. */
  59. function multinet_totalips_count($first_ip, $last_ip) {
  60. $first = ip2int($first_ip);
  61. $last = ip2int($last_ip);
  62. $result = 0;
  63. for ($i = $first; $i <= $last; $i++) {
  64. $curIpOffset = int2ip($i);
  65. if (!preg_match("#\.(0|1|255)$#", $curIpOffset)) {
  66. $result++;
  67. }
  68. }
  69. return ($result);
  70. }
  71. /**
  72. * Renders IP usage stats in existing networks. Reacts to allnets GET parameter.
  73. *
  74. * @global object $ubillingConfig
  75. * @global object $branchControl
  76. *
  77. * @return string
  78. */
  79. function web_FreeIpStats() {
  80. global $ubillingConfig;
  81. $result = '';
  82. $data = multinet_getFreeIpStats();
  83. //checking service filters
  84. if (wf_CheckGet(array('allnets'))) {
  85. $servFlag = false;
  86. } else {
  87. $servFlag = true;
  88. }
  89. // branches support
  90. if ($ubillingConfig->getAlterParam('BRANCHES_ENABLED')) {
  91. global $branchControl;
  92. $branchControl->loadServices();
  93. }
  94. $cells = wf_TableCell(__('ID'));
  95. $cells .= wf_TableCell(__('Network/CIDR'));
  96. $cells .= wf_TableCell(__('Total') . ' ' . __('IP'));
  97. $cells .= wf_TableCell(__('Used') . ' ' . __('IP'));
  98. $cells .= wf_TableCell(__('Free') . ' ' . __('IP'));
  99. $cells .= wf_TableCell(__('Service'));
  100. $rows = wf_TableRow($cells, 'row1');
  101. if (!empty($data)) {
  102. foreach ($data as $io => $each) {
  103. if ($servFlag) {
  104. if (!empty($each['service'])) {
  105. $appendResult = true;
  106. } else {
  107. $appendResult = false;
  108. }
  109. } else {
  110. $appendResult = true;
  111. }
  112. //branch resctrictions control
  113. if ($ubillingConfig->getAlterParam('BRANCHES_ENABLED')) {
  114. if ($branchControl->isMyService($each['serviceid'])) {
  115. $appendResult = true;
  116. } else {
  117. $appendResult = false;
  118. }
  119. }
  120. if ($appendResult) {
  121. $free = $each['total'] - $each['used'];
  122. $fontColor = ($free <= 5) ? '#a90000' : '';
  123. $cells = wf_TableCell($io);
  124. $cells .= wf_TableCell($each['desc']);
  125. $cells .= wf_TableCell($each['total']);
  126. $cells .= wf_TableCell($each['used']);
  127. $cells .= wf_TableCell(wf_tag('font', false, '', 'color="' . $fontColor . '"') . $free . wf_tag('font', false));
  128. $cells .= wf_TableCell($each['service']);
  129. $rows .= wf_TableRow($cells, 'row5');
  130. }
  131. }
  132. }
  133. $result .= wf_TableBody($rows, '100%', 0, 'sortable');
  134. return ($result);
  135. }
  136. /**
  137. * Renders list of available networks
  138. *
  139. * @global object $ubillingConfig
  140. *
  141. * @return void
  142. */
  143. function multinet_show_available_networks() {
  144. global $ubillingConfig;
  145. $query = "SELECT * from `networks`";
  146. $networks = simple_queryall($query);
  147. $cells = wf_TableCell(__('ID'));
  148. $cells .= wf_TableCell(__('First IP'));
  149. $cells .= wf_TableCell(__('Last IP'));
  150. $cells .= wf_TableCell(__('Network/CIDR'));
  151. $cells .= wf_TableCell(__('Network type'));
  152. $cells .= wf_TableCell(__('Actions'));
  153. $rows = wf_TableRow($cells, 'row1');
  154. if (!empty($networks)) {
  155. foreach ($networks as $network) {
  156. $cells = wf_TableCell($network['id']);
  157. $cells .= wf_TableCell($network['startip']);
  158. $cells .= wf_TableCell($network['endip']);
  159. $cells .= wf_TableCell($network['desc']);
  160. $cells .= wf_TableCell($network['nettype']);
  161. $actions = wf_JSAlert('?module=multinet&deletenet=' . $network['id'], web_delete_icon(), 'Removing this may lead to irreparable results');
  162. $actions .= wf_JSAlert('?module=multinet&editnet=' . $network['id'], web_edit_icon(), 'Are you serious');
  163. $cells .= wf_TableCell($actions);
  164. $rows .= wf_TableRow($cells, 'row5');
  165. }
  166. }
  167. $result = wf_TableBody($rows, '100%', '0', 'sortable');
  168. $statsControls = wf_Link('?module=multinet&freeipstats=true', wf_img_sized('skins/icon_stats.gif', __('IP usage stats'), 16));
  169. show_window(__('Networks') . ' ' . $statsControls, $result);
  170. }
  171. /**
  172. * Renders network editing form
  173. *
  174. * @global object $ubillingConfig
  175. *
  176. * @param int $netid
  177. *
  178. * @return void
  179. */
  180. function multinet_show_neteditform($netid) {
  181. global $ubillingConfig;
  182. $netid = vf($netid, 3);
  183. $netdata = multinet_get_network_params($netid);
  184. $sup = wf_tag('sup') . '*' . wf_tag('sup', true);
  185. $inputs = wf_HiddenInput('netedit', 'true');
  186. $inputs .= wf_TextInput('editstartip', __('First IP') . $sup, $netdata['startip'], true, '20', 'ip');
  187. $inputs .= wf_TextInput('editendip', __('Last IP') . $sup, $netdata['endip'], true, '20', 'ip');
  188. $inputs .= multinet_nettype_selector($netdata['nettype']) . ' ' . __('Network type') . wf_tag('br');
  189. $inputs .= wf_TextInput('editdesc', __('Network/CIDR') . $sup, $netdata['desc'], true, '20', 'net-cidr');
  190. $inputs .= wf_Submit(__('Save'));
  191. $form = wf_Form('', "POST", $inputs, 'glamour');
  192. $form .= wf_BackLink('?module=multinet');
  193. show_window(__('Edit'), $form);
  194. }
  195. /**
  196. * Renders service editing form
  197. *
  198. * @param int $serviceid
  199. *
  200. * @return void
  201. */
  202. function multinet_show_serviceeditform($serviceid) {
  203. $serviceid = vf($serviceid, 3);
  204. $servicedata = multinet_get_service_params($serviceid);
  205. $inputs = wf_HiddenInput('serviceedit', 'true');
  206. $inputs .= multinet_network_selector($servicedata['netid']) . ' ' . __('Service network') . wf_tag('br');
  207. $inputs .= wf_TextInput('editservicename', __('Service description') . wf_tag('sup') . '*' . wf_tag('sup', true), $servicedata['desc'], true, 15);
  208. $inputs .= wf_Submit(__('Save'));
  209. $form = wf_Form('', 'POST', $inputs, 'glamour');
  210. $form .= wf_BackLink('?module=multinet');
  211. show_window(__('Edit'), $form);
  212. }
  213. /**
  214. * Deletes some host from nethosts by its IP
  215. *
  216. * @param string $ip
  217. *
  218. * @return void
  219. */
  220. function multinet_delete_host($ip) {
  221. $query = "DELETE from `nethosts` WHERE `ip`='" . $ip . "'";
  222. nr_query($query);
  223. log_register("DELETE MultiNetHost " . $ip);
  224. }
  225. /**
  226. * Returns networks selector control
  227. *
  228. * @param int $currentnetid
  229. *
  230. * @return string
  231. */
  232. function multinet_network_selector($currentnetid = '') {
  233. $allnetworks = multinet_get_all_networks();
  234. $tmpArr = array();
  235. if (!empty($allnetworks)) {
  236. foreach ($allnetworks as $io => $eachnetwork) {
  237. $tmpArr[$eachnetwork['id']] = $eachnetwork['desc'];
  238. }
  239. }
  240. $result = wf_Selector('networkselect', $tmpArr, '', $currentnetid, false);
  241. return ($result);
  242. }
  243. /**
  244. * Returns unprocessed array of available networks with their data
  245. *
  246. * @return array
  247. */
  248. function multinet_get_all_networks() {
  249. $query = "SELECT * from `networks`";
  250. $result = simple_queryall($query);
  251. return ($result);
  252. }
  253. /**
  254. * Returns unprocessed array of available networks with their data as netid=>netdata
  255. *
  256. * @return array
  257. */
  258. function multinet_get_all_networks_assoc() {
  259. $result = array();
  260. $query = "SELECT * from `networks`";
  261. $all = simple_queryall($query);
  262. if (!empty($all)) {
  263. foreach ($all as $io => $each) {
  264. $result[$each['id']] = $each;
  265. }
  266. }
  267. return ($result);
  268. }
  269. /**
  270. * Returns selector of available networks types
  271. *
  272. * @param string $curnettype
  273. *
  274. * @return string
  275. */
  276. function multinet_nettype_selector($curnettype = '') {
  277. global $ubillingConfig;
  278. $dhcpFlag = $ubillingConfig->getAlterParam('DHCP_ENABLED');
  279. $opt82Flag = $ubillingConfig->getAlterParam('OPT82_ENABLED');
  280. $pppFlag = $ubillingConfig->getAlterParam('PPP_ENABLED');
  281. $params = array();
  282. if ($dhcpFlag) {
  283. $params += array(
  284. 'dhcpstatic' => 'DHCP static hosts',
  285. 'dhcpdynamic' => 'DHCP dynamic hosts',
  286. );
  287. }
  288. if ($opt82Flag) {
  289. $params += array(
  290. 'dhcp82' => 'DHCP option 82',
  291. 'dhcp82_vpu' => 'DHCP option 82 + vlan per user',
  292. 'dhcp82_bdcom' => 'DHCP option 82 + mac onu (BDCOM)',
  293. 'dhcp82_zte' => 'DHCP option 82 + mac onu (ZTE)',
  294. );
  295. }
  296. if ($pppFlag) {
  297. $params += array(
  298. 'pppstatic' => 'PPP static network',
  299. 'pppdynamic' => 'PPP dynamic network',
  300. );
  301. }
  302. $params += array(
  303. 'other' => 'Other type'
  304. );
  305. $result = wf_Selector('nettypesel', $params, '', $curnettype, false);
  306. return ($result);
  307. }
  308. /**
  309. * Renders network creation form
  310. *
  311. * @global object $ubillingConfig
  312. *
  313. * @return void
  314. */
  315. function multinet_show_networks_create_form() {
  316. global $ubillingConfig;
  317. $sup = wf_tag('sup') . '*' . wf_tag('sup', true);
  318. $inputs = wf_HiddenInput('addnet', 'true');
  319. $inputs .= wf_TextInput('firstip', __('First IP') . $sup, '', true, '20', 'ip');
  320. $inputs .= wf_TextInput('lastip', __('Last IP') . $sup, '', true, '20', 'ip');
  321. $inputs .= multinet_nettype_selector() . ' ' . __('Network type') . wf_tag('br');
  322. $inputs .= wf_TextInput('desc', __('Network/CIDR') . $sup, '', true, '20', 'net-cidr');
  323. $inputs .= wf_Submit(__('Create'));
  324. $form = wf_Form('', 'POST', $inputs, 'glamour');
  325. show_window(__('Add network'), $form);
  326. }
  327. /**
  328. * Renders available services list with some controls
  329. *
  330. * @return void
  331. */
  332. function multinet_show_available_services() {
  333. $allservices = multinet_get_services();
  334. $allNetworkParams = multinet_get_all_networks_assoc();
  335. $tablecells = wf_TableCell(__('ID'));
  336. $tablecells .= wf_TableCell(__('Network'));
  337. $tablecells .= wf_TableCell(__('Service name'));
  338. $tablecells .= wf_TableCell(__('Actions'));
  339. $tablerows = wf_TableRow($tablecells, 'row1');
  340. if (!empty($allservices)) {
  341. foreach ($allservices as $io => $eachservice) {
  342. $netdesc = (empty($allNetworkParams[$eachservice['netid']]) ? __('Network does not exist anymore') : $allNetworkParams[$eachservice['netid']]['desc']);
  343. $tablecells = wf_TableCell($eachservice['id']);
  344. $tablecells .= wf_TableCell($netdesc);
  345. $tablecells .= wf_TableCell($eachservice['desc']);
  346. $actionlinks = wf_JSAlert('?module=multinet&deleteservice=' . $eachservice['id'], web_delete_icon(), 'Removing this may lead to irreparable results');
  347. $actionlinks .= wf_JSAlert('?module=multinet&editservice=' . $eachservice['id'], web_edit_icon(), 'Are you serious');
  348. $tablecells .= wf_TableCell($actionlinks);
  349. $tablerows .= wf_TableRow($tablecells, 'row5');
  350. }
  351. }
  352. $result = wf_TableBody($tablerows, '100%', '0', 'sortable');
  353. show_window(__('Services'), $result);
  354. }
  355. /**
  356. * Returns array of available services
  357. *
  358. * @return array
  359. */
  360. function multinet_get_services() {
  361. global $ubillingConfig;
  362. if ($ubillingConfig->getAlterParam('DROPDOWN_LISTS_IPSERVICE_ORDER_BY_DESCR')) {
  363. $query = "SELECT * FROM `services` ORDER BY `desc`";
  364. } else {
  365. $query = "SELECT * FROM `services` ORDER BY `id`";
  366. }
  367. $result = simple_queryall($query);
  368. return ($result);
  369. }
  370. /**
  371. * Returns services selector control
  372. *
  373. * @global object $ubillingConfig
  374. * @global object $branchControl
  375. *
  376. * @return string
  377. */
  378. function multinet_service_selector() {
  379. global $ubillingConfig;
  380. $tmpArr = array();
  381. $allNetsStats = array();
  382. if ($ubillingConfig->getAlterParam('BRANCHES_ENABLED')) {
  383. global $branchControl;
  384. $branchControl->loadServices();
  385. }
  386. $freeIpStatsFlag = $ubillingConfig->getAlterParam('USERREG_FREEIP_STATS');
  387. if ($freeIpStatsFlag == 2 or $freeIpStatsFlag == 3) {
  388. $allNetsStats = multinet_getFreeIpStats();
  389. }
  390. $allservices = multinet_get_services();
  391. if (!empty($allservices)) {
  392. foreach ($allservices as $io => $eachservice) {
  393. if ($ubillingConfig->getAlterParam('BRANCHES_ENABLED')) {
  394. if ($branchControl->isMyService($eachservice['id'])) {
  395. $tmpArr[$eachservice['id']] = $eachservice['desc'];
  396. //optional free IP stats for branch restricted users
  397. if (isset($allNetsStats[$eachservice['netid']])) {
  398. $tmpArr[$eachservice['id']] .= ' (' . __('Free') . ' ' . $allNetsStats[$eachservice['netid']]['free'] . ')';
  399. }
  400. }
  401. } else {
  402. $tmpArr[$eachservice['id']] = $eachservice['desc'];
  403. //optional free IP stats for all nets
  404. if (isset($allNetsStats[$eachservice['netid']])) {
  405. $tmpArr[$eachservice['id']] .= ' (' . __('Free') . ' ' . $allNetsStats[$eachservice['netid']]['free'] . ')';
  406. }
  407. }
  408. }
  409. }
  410. $result = wf_Selector('serviceselect', $tmpArr, '', '', false, false);
  411. return ($result);
  412. }
  413. /**
  414. * Renders network service creation form
  415. *
  416. * @return void
  417. */
  418. function multinet_show_service_add_form() {
  419. $inputs = wf_HiddenInput('serviceadd', 'true');
  420. $inputs .= multinet_network_selector() . ' ' . __('Service network') . wf_tag('br');
  421. $inputs .= wf_TextInput('servicename', __('Service description'), '', true, 15);
  422. $inputs .= wf_Submit(__('Create'));
  423. $form = wf_Form('', 'POST', $inputs, 'glamour');
  424. show_window(__('Add service'), $form);
  425. }
  426. /**
  427. * Creates new multinet network in database
  428. *
  429. * @param string $desc
  430. * @param string $firstip
  431. * @param string $lastip
  432. * @param string $nettype
  433. *
  434. * @return void
  435. */
  436. function multinet_add_network($desc, $firstip, $lastip, $nettype) {
  437. $desc = mysql_real_escape_string($desc);
  438. $firstip = vf($firstip);
  439. $lastip = vf($lastip);
  440. $nettype = vf($nettype);
  441. $query = "INSERT INTO `networks` (`id`, `desc`, `startip`, `endip`, `nettype`, `use_radius` ) VALUES
  442. (NULL, '" . $desc . "', '" . $firstip . "', '" . $lastip . "', '" . $nettype . "', '0');";
  443. nr_query($query);
  444. log_register('ADD MultiNetNet `' . $desc . '`');
  445. }
  446. /**
  447. * Checks is network used by some network hosts or not
  448. *
  449. * @param int $network_id
  450. *
  451. * @return bool
  452. */
  453. function multinet_network_is_used($network_id) {
  454. $network_id = vf($network_id, 3);
  455. $query = "SELECT `id` from `nethosts` WHERE `netid`='" . $network_id . "'";
  456. $allhosts = simple_query($query);
  457. if (!empty($allhosts)) {
  458. return (true);
  459. } else {
  460. return (false);
  461. }
  462. }
  463. /**
  464. * Deletes some multinet network from database
  465. *
  466. * @param type $network_id
  467. *
  468. * @return void
  469. */
  470. function multinet_delete_network($network_id) {
  471. $network_id = vf($network_id, 3);
  472. $query = "DELETE FROM `networks` WHERE `id`='" . $network_id . "'";
  473. nr_query($query);
  474. log_register('DELETE MultiNetNet [' . $network_id . ']');
  475. }
  476. /**
  477. * Creates new network service in database
  478. *
  479. * @param int $net
  480. * @param string $desc
  481. *
  482. * @return void
  483. */
  484. function multinet_add_service($net, $desc) {
  485. $net = vf($net, 3);
  486. $desc = mysql_real_escape_string($desc);
  487. $query = "INSERT INTO `services` (`id`,`netid`,`desc` ) VALUES (NULL, '" . $net . "', '" . $desc . "');";
  488. nr_query($query);
  489. log_register('ADD MultiNetNetService `' . $desc . '`');
  490. }
  491. /**
  492. * Returns array of existing network parameters
  493. *
  494. * @param int $network_id
  495. *
  496. * @return array
  497. */
  498. function multinet_get_network_params($network_id) {
  499. $network_id = vf($network_id, 3);
  500. $query = 'SELECT * from `networks` WHERE `id`="' . $network_id . '"';
  501. $result = simple_query($query);
  502. if (empty($result)) {
  503. $result = array();
  504. }
  505. return ($result);
  506. }
  507. /**
  508. * Returns array of existing network parameters
  509. *
  510. * @param var $login
  511. *
  512. * @return array
  513. */
  514. function multinet_get_network_params_by_login($login) {
  515. $result = array();
  516. $query = 'SELECT `networks`.* FROM `users`
  517. INNER JOIN `nethosts` USING (`ip`)
  518. INNER JOIN `networks` ON `nethosts`.`netid` = `networks`.`id`
  519. WHERE `login`="' . $login . '"';
  520. $result = simple_query($query);
  521. return ($result);
  522. }
  523. /**
  524. * Returns array of existing service parameters
  525. *
  526. * @param int $serviceid
  527. *
  528. * @return array
  529. */
  530. function multinet_get_service_params($serviceid) {
  531. $serviceid = vf($serviceid, 3);
  532. $query = 'SELECT * from `services` WHERE `id`="' . $serviceid . '"';
  533. $result = simple_query($query);
  534. return ($result);
  535. }
  536. /**
  537. * Deletes existing network service from database
  538. *
  539. * @param int $service_id
  540. *
  541. * @return void
  542. */
  543. function multinet_delete_service($service_id) {
  544. $service_id = vf($service_id, 3);
  545. $query = "DELETE FROM `services` WHERE `id`='" . $service_id . "'";
  546. nr_query($query);
  547. log_register('DELETE MultiNetService [' . $service_id . ']');
  548. }
  549. /**
  550. * Returns list of all existing dhcp-oriented networks
  551. *
  552. * @return array
  553. */
  554. function multinet_get_dhcp_networks() {
  555. $query = "SELECT * from `networks` where `nettype` LIKE 'dhcp%'";
  556. $alldhcps = simple_queryall($query);
  557. return ($alldhcps);
  558. }
  559. /**
  560. * Returns dhcp handler data by network ID
  561. *
  562. * @param int $netid
  563. *
  564. * @return array
  565. */
  566. function dhcp_get_data_by_netid($netid) {
  567. $netid = vf($netid, 3);
  568. $query = "SELECT * from `dhcp` where `netid`='" . $netid . "'";
  569. $result = simple_query($query);
  570. return ($result);
  571. }
  572. /**
  573. * Returns all dhcp handlers data as netid=>dhcpdata
  574. *
  575. * @return array
  576. */
  577. function dhcp_get_all_data_assoc() {
  578. $result = array();
  579. $query = "SELECT * from `dhcp`";
  580. $all = simple_queryall($query);
  581. if (!empty($all)) {
  582. foreach ($all as $io => $each) {
  583. $result[$each['netid']] = $each;
  584. }
  585. }
  586. return ($result);
  587. }
  588. /**
  589. * Rebuilds dhcp subnet config with some static hosts
  590. *
  591. * @param int $netid
  592. * @param string $confname
  593. * @param bool $ddns
  594. * @param array $loginIps
  595. * @param array $allNetHosts
  596. *
  597. * @return void
  598. */
  599. function handle_dhcp_rebuild_static($netid, $confname, $ddns = false, $loginIps = array(), $allNetHosts = array()) {
  600. $query = "SELECT * from `nethosts` WHERE `netid`='" . $netid . "'";
  601. // check haz it .conf name or not?
  602. if (!empty($confname)) {
  603. $allhosts = array();
  604. if (!empty($allNetHosts)) {
  605. foreach ($allNetHosts as $io => $each) {
  606. if ($each['netid'] == $netid) {
  607. $allhosts[] = $each;
  608. }
  609. }
  610. }
  611. $confpath = 'multinet/' . $confname;
  612. $result = '';
  613. if (!empty($allhosts)) {
  614. foreach ($allhosts as $io => $eachhost) {
  615. //default IP based hosts
  616. if (!$ddns) {
  617. $dhcphostname = 'm' . str_replace('.', 'x', $eachhost['ip']);
  618. } else {
  619. if (isset($loginIps[$eachhost['ip']])) {
  620. $dhcphostname = $loginIps[$eachhost['ip']];
  621. } else {
  622. $dhcphostname = 'unknown' . zb_rand_string(8);
  623. }
  624. }
  625. $result .= '
  626. host ' . $dhcphostname . ' {
  627. hardware ethernet ' . $eachhost['mac'] . ';
  628. fixed-address ' . $eachhost['ip'] . ';
  629. }' . "\n";
  630. }
  631. file_put_contents($confpath, $result);
  632. } else {
  633. file_put_contents($confpath, $result);
  634. }
  635. }
  636. }
  637. /**
  638. * Rebuilds dhcp subnet config with option82 hosts
  639. *
  640. * @param int $netid
  641. * @param string $confname
  642. *
  643. * @return void
  644. */
  645. function handle_dhcp_rebuild_option82($netid, $confname) {
  646. $query = "SELECT `login`,`users`.`ip` as `ip`,`option`,`port`,`switches`.`ip` AS `swip`,`swid`
  647. FROM `users`
  648. INNER JOIN `nethosts` USING (ip)
  649. LEFT JOIN (SELECT * FROM `switchportassign`) as switchportassign USING (login)
  650. LEFT JOIN `switches` ON (`switchportassign`.switchid=`switches`.`id`)
  651. WHERE `netid` = '" . $netid . "'";
  652. if (!empty($confname)) {
  653. $confpath = 'multinet/' . $confname;
  654. $allhosts = simple_queryall($query);
  655. $result = '';
  656. if (!empty($allhosts)) {
  657. $customTemplate = file_get_contents(CONFIG_PATH . "dhcp/option82.template");
  658. if (empty($customTemplate)) {
  659. $customTemplate = '
  660. class "{HOSTNAME}" {
  661. match if binary-to-ascii (16, 8, "", option agent.remote-id) = "{REMOTEID}" and binary-to-ascii (10, 8, "", option agent.circuit-id) = "{CIRCUITID}";
  662. }
  663. pool {
  664. range {IP};
  665. allow members of "{HOSTNAME}";
  666. }
  667. ' . "\n";
  668. }
  669. foreach ($allhosts as $io => $eachhost) {
  670. $parseTemplate = $customTemplate;
  671. $dhcphostname = 'm' . str_replace('.', 'x', $eachhost['ip']);
  672. $options = explode('|', $eachhost['option']);
  673. if (isset($options[1])) {
  674. $parseTemplate = str_ireplace('{HOSTNAME}', $dhcphostname, $parseTemplate);
  675. $parseTemplate = str_ireplace('{REMOTEID}', $options[0], $parseTemplate);
  676. $parseTemplate = str_ireplace('{CIRCUITID}', $options[1], $parseTemplate);
  677. $parseTemplate = str_ireplace('{IP}', $eachhost['ip'], $parseTemplate);
  678. $parseTemplate = str_ireplace('{SWITCHIP}', $eachhost['swip'], $parseTemplate);
  679. $parseTemplate = str_ireplace('{SWITCHMAC}', $eachhost['swid'], $parseTemplate);
  680. $parseTemplate = str_ireplace('{SWITCHPORT}', $eachhost['port'], $parseTemplate);
  681. $result .= $parseTemplate;
  682. } else {
  683. if (preg_match('/{SWITCHIP}|{SWITCHMAC}|{PORT}/', $customTemplate)) {
  684. $parseTemplate = str_ireplace('{HOSTNAME}', $dhcphostname, $parseTemplate);
  685. $parseTemplate = str_ireplace('{IP}', $eachhost['ip'], $parseTemplate);
  686. $parseTemplate = str_ireplace('{SWITCHIP}', $eachhost['swip'], $parseTemplate);
  687. $parseTemplate = str_ireplace('{SWITCHMAC}', $eachhost['swid'], $parseTemplate);
  688. $parseTemplate = str_ireplace('{SWITCHPORT}', $eachhost['port'], $parseTemplate);
  689. $result .= $parseTemplate;
  690. }
  691. }
  692. }
  693. file_put_contents($confpath, $result);
  694. } else {
  695. file_put_contents($confpath, $result);
  696. }
  697. }
  698. }
  699. /**
  700. * Rebuilds dhcp subnet config with option82 VPU hosts
  701. *
  702. * @param int $netid
  703. * @param string $confname
  704. *
  705. * @return void
  706. */
  707. function handle_dhcp_rebuild_option82_vpu($netid, $confname) {
  708. $query = "SELECT * from `nethosts` WHERE `netid`='" . $netid . "'";
  709. if (!empty($confname)) {
  710. $confpath = 'multinet/' . $confname;
  711. $allhosts = simple_queryall($query);
  712. $allVlans = GetAllUserVlan();
  713. $allIps = GetAllUserIp();
  714. $result = '';
  715. if (!empty($allhosts)) {
  716. $customTemplate = file_get_contents(CONFIG_PATH . "dhcp/option82_vpu.template");
  717. if (empty($customTemplate)) {
  718. $customTemplate = '
  719. class "{HOSTNAME}" { match if binary-to-ascii (16, 8, "", option agent.remote-id) = "{REMOTEID}" and binary-to-ascii(10, 16, "", substring(option agent.circuit-id,2,2)) = "{CIRCUITID}"; }
  720. pool {
  721. range {IP};
  722. allow members of "{HOSTNAME}";
  723. }
  724. ' . "\n";
  725. }
  726. foreach ($allhosts as $io => $eachhost) {
  727. $login = $allIps[$eachhost['ip']];
  728. if (isset($allVlans[$login])) {
  729. //$netid = GetNetidByIp($eachhost['ip']);
  730. $remote = GetTermRemoteByNetid($netid);
  731. $vlan = $allVlans[$login];
  732. $dhcphostname = 'm' . str_replace('.', 'x', $eachhost['ip']);
  733. if (!empty($vlan)) {
  734. $parseTemplate = $customTemplate;
  735. $parseTemplate = str_ireplace('{HOSTNAME}', $dhcphostname, $parseTemplate);
  736. $parseTemplate = str_ireplace('{CIRCUITID}', $vlan, $parseTemplate);
  737. $parseTemplate = str_ireplace('{IP}', $eachhost['ip'], $parseTemplate);
  738. $parseTemplate = str_ireplace('{REMOTEID}', $remote, $parseTemplate);
  739. $result .= $parseTemplate;
  740. }
  741. }
  742. }
  743. file_put_contents($confpath, $result);
  744. } else {
  745. file_put_contents($confpath, $result);
  746. }
  747. }
  748. }
  749. /**
  750. * Rebuilds dhcp subnet config with option82 bdcom hosts
  751. *
  752. * @param int $netid
  753. * @param string $confname
  754. *
  755. * @return void
  756. */
  757. function handle_dhcp_rebuild_option82_bdcom($netid, $confname) {
  758. $query = "SELECT * from `nethosts` WHERE `netid`='" . $netid . "'";
  759. if (!empty($confname)) {
  760. $confpath = 'multinet/' . $confname;
  761. $allhosts = simple_queryall($query);
  762. $allOnu = GetAllUserOnu();
  763. $allIps = GetAllUserIp();
  764. $result = '';
  765. if (!empty($allhosts)) {
  766. $customTemplate = file_get_contents(CONFIG_PATH . "dhcp/option82_bdcom.template");
  767. if (empty($customTemplate)) {
  768. $customTemplate = '
  769. class "{HOSTNAME}" { match if binary-to-ascii(16,8,":",substring(option agent.remote-id,0,6)) = "{CIRCUITID}"; }
  770. pool {
  771. range {IP};
  772. allow members of "{HOSTNAME}";
  773. }
  774. ' . "\n";
  775. }
  776. foreach ($allhosts as $io => $eachhost) {
  777. $login = $allIps[$eachhost['ip']];
  778. $mac = '';
  779. if (isset($allOnu[$login]) and !empty($allOnu[$login])) {
  780. $macFull = explode(":", $allOnu[$login]['mac']);
  781. foreach ($macFull as $eachOctet) {
  782. $validOctet = preg_replace('/^0/', '', $eachOctet);
  783. $mac .= $validOctet . ':';
  784. }
  785. $mac_len = strlen($mac);
  786. $mac = substr($mac, 0, $mac_len - 1);
  787. $dhcphostname = 'm' . str_replace('.', 'x', $eachhost['ip']);
  788. $parseTemplate = $customTemplate;
  789. $parseTemplate = str_ireplace('{HOSTNAME}', $dhcphostname, $parseTemplate);
  790. $parseTemplate = str_ireplace('{CIRCUITID}', $mac, $parseTemplate);
  791. $parseTemplate = str_ireplace('{IP}', $eachhost['ip'], $parseTemplate);
  792. $result .= $parseTemplate;
  793. }
  794. }
  795. file_put_contents($confpath, $result);
  796. } else {
  797. file_put_contents($confpath, $result);
  798. }
  799. }
  800. }
  801. /**
  802. * Rebuilds dhcp subnet config with option82 zte hosts
  803. *
  804. * @param int $netid
  805. * @param string $confname
  806. *
  807. * @return void
  808. */
  809. function handle_dhcp_rebuild_option82_zte($netid, $confname) {
  810. $query = "SELECT * from `nethosts` WHERE `netid`='" . $netid . "'";
  811. if (!empty($confname)) {
  812. $confpath = 'multinet/' . $confname;
  813. $allhosts = simple_queryall($query);
  814. $allOnu = GetAllUserOnu();
  815. $allIps = GetAllUserIp();
  816. $allOltSnmpTemplates = loadOltSnmpTemplates();
  817. $result = '';
  818. if (!empty($allhosts)) {
  819. $customTemplate = file_get_contents(CONFIG_PATH . "dhcp/option82_zte.template");
  820. if (empty($customTemplate)) {
  821. $customTemplate = '
  822. class "{HOSTNAME}" { match if substring(option agent.circuit-id,49,12) = "{CIRCUITID}"; }
  823. pool {
  824. range {IP};
  825. allow members of "{HOSTNAME}";
  826. }
  827. ' . "\n";
  828. }
  829. foreach ($allhosts as $io => $eachhost) {
  830. $login = $allIps[$eachhost['ip']];
  831. $onuId = '';
  832. $onuIdentifier = '';
  833. if (isset($allOnu[$login]) and !empty($allOnu[$login])) {
  834. $oltId = $allOnu[$login]['oltid'];
  835. if (isset($allOltSnmpTemplates[$oltId])) {
  836. if ($allOltSnmpTemplates[$oltId]['signal']['SIGNALMODE'] == 'ZTE') {
  837. $onuIdentifier = explode(":", $allOnu[$login]['mac']);
  838. } elseif ($allOltSnmpTemplates[$oltId]['signal']['SIGNALMODE'] == 'ZTE_GPON') {
  839. if (!empty($allOnu[$login]['serial'])) {
  840. $onuIdentifier = explode(":", $allOnu[$login]['serial']);
  841. }
  842. }
  843. }
  844. if (!empty($onuIdentifier)) {
  845. foreach ($onuIdentifier as $eachOctet) {
  846. $onuId .= strtoupper($eachOctet);
  847. }
  848. $dhcphostname = 'm' . str_replace('.', 'x', $eachhost['ip']);
  849. $parseTemplate = $customTemplate;
  850. $parseTemplate = str_ireplace('{HOSTNAME}', $dhcphostname, $parseTemplate);
  851. $parseTemplate = str_ireplace('{CIRCUITID}', $onuId, $parseTemplate);
  852. $parseTemplate = str_ireplace('{IP}', $eachhost['ip'], $parseTemplate);
  853. $result .= $parseTemplate;
  854. }
  855. }
  856. }
  857. file_put_contents($confpath, $result);
  858. } else {
  859. file_put_contents($confpath, $result);
  860. }
  861. }
  862. }
  863. /**
  864. * Generates some static ppp secrets file
  865. *
  866. * @param int $netid
  867. *
  868. * @return void
  869. */
  870. function handle_ppp_rebuild_static($netid) {
  871. $query = "SELECT * from `nethosts` WHERE `netid`='" . $netid . "'";
  872. $confpath = 'multinet/ppp.' . $netid . '.static';
  873. $allhosts = simple_queryall($query);
  874. $result = '';
  875. if (!empty($allhosts)) {
  876. foreach ($allhosts as $io => $eachhost) {
  877. $accdata_q = "SELECT `login`,`Password` from `users` WHERE `IP`='" . $eachhost['ip'] . "'";
  878. $accdata = simple_query($accdata_q);
  879. $result .= $accdata['login'] . ' ' . $accdata['Password'] . ' ' . $eachhost['ip'] . "\n";
  880. }
  881. }
  882. file_put_contents($confpath, $result);
  883. }
  884. /**
  885. * Generates dynamic ppp secrets file
  886. *
  887. * @param int $netid
  888. *
  889. * @return void
  890. */
  891. function handle_ppp_rebuild_dynamic($netid) {
  892. $query = "SELECT * from `nethosts` WHERE `netid`='" . $netid . "'";
  893. $confpath = 'multinet/ppp.' . $netid . '.dynamic';
  894. $allhosts = simple_queryall($query);
  895. $result = '';
  896. if (!empty($allhosts)) {
  897. foreach ($allhosts as $io => $eachhost) {
  898. $accdata_q = "SELECT `login`,`Password` from `users` WHERE `IP`='" . $eachhost['ip'] . "'";
  899. $accdata = simple_query($accdata_q);
  900. $result .= $accdata['login'] . ' ' . $accdata['Password'] . "\n";
  901. }
  902. }
  903. file_put_contents($confpath, $result);
  904. }
  905. /**
  906. * Returns template with replaced macro
  907. *
  908. * @param string $templatebody
  909. * @param array $templatedata
  910. *
  911. * @return string
  912. */
  913. function multinet_ParseTemplate($templatebody, $templatedata) {
  914. foreach ($templatedata as $field => $data) {
  915. $templatebody = str_ireplace($field, $data, $templatebody);
  916. }
  917. return ($templatebody);
  918. }
  919. /**
  920. * Converts CIDR mask into decimal like 24 => 255.255.255.0
  921. *
  922. * @param int $mask_bits
  923. *
  924. * @return string
  925. */
  926. function multinet_cidr2mask($mask_bits) {
  927. if ($mask_bits > 31 || $mask_bits < 0)
  928. return ("0.0.0.0");
  929. $host_bits = 32 - $mask_bits;
  930. $num_hosts = pow(2, $host_bits) - 1;
  931. $netmask = ip2int("255.255.255.255") - $num_hosts;
  932. return int2ip($netmask);
  933. }
  934. /**
  935. * Rebuilds dhcp global config file
  936. *
  937. * @global object $ubillingConfig
  938. *
  939. * @return void
  940. */
  941. function multinet_rebuild_globalconf() {
  942. global $ubillingConfig;
  943. $global_template = file_get_contents("config/dhcp/global.template");
  944. $subnets_template = file_get_contents("config/dhcp/subnets.template");
  945. $allNetsData = multinet_get_all_networks_assoc();
  946. $alldhcpsubnets = dhcp_get_all_data_assoc();
  947. $allMembers_q = "SELECT `ip` from `nethosts` WHERE `option` != 'NULL'";
  948. $allMembers = simple_queryall($allMembers_q);
  949. $membersMacroContent = '';
  950. $vlanMembersMacroContent = '';
  951. $onuMembersMacroContent = '';
  952. $subnets = '';
  953. if (!empty($allMembers)) {
  954. foreach ($allMembers as $ix => $eachMember) {
  955. $memberClass = 'm' . str_replace('.', 'x', $eachMember['ip']);;
  956. $membersMacroContent .= 'deny members of "' . $memberClass . '";' . "\n";
  957. }
  958. }
  959. if ($ubillingConfig->getAlterParam('VLANGEN_SUPPORT')) {
  960. $vlanMembers_q = "SELECT `ip` FROM `users` WHERE `login` IN(SELECT `login` FROM `vlanhosts`);";
  961. $allVlanMembers = simple_queryall($vlanMembers_q);
  962. if (!empty($allVlanMembers)) {
  963. foreach ($allVlanMembers as $ivl => $eachVlanMember) {
  964. $memberVlanClass = 'm' . str_replace('.', 'x', $eachVlanMember['ip']);
  965. $vlanMembersMacroContent .= 'deny members of "' . $memberVlanClass . '";' . "\n";
  966. }
  967. }
  968. }
  969. $onuMembers_q = "SELECT `ip` FROM `nethosts` WHERE `netid` IN (SELECT `id` FROM `networks` WHERE `nettype` = 'dhcp82_bdcom' or `nettype` = 'dhcp82_zte');";
  970. $allOnuMembers = simple_queryall($onuMembers_q);
  971. if (!empty($allOnuMembers)) {
  972. foreach ($allOnuMembers as $index => $eachOnuMember) {
  973. $memberOnuClass = 'm' . str_replace('.', 'x', $eachOnuMember['ip']);
  974. $onuMembersMacroContent .= 'deny members of "' . $memberOnuClass . '";' . "\n";
  975. }
  976. }
  977. if (!empty($alldhcpsubnets)) {
  978. foreach ($alldhcpsubnets as $io => $eachnet) {
  979. //network really exists?
  980. if (isset($allNetsData[$eachnet['netid']])) {
  981. $netdata = $allNetsData[$eachnet['netid']];
  982. $templatedata['{STARTIP}'] = $netdata['startip'];
  983. $templatedata['{ENDIP}'] = $netdata['endip'];
  984. $templatedata['{CIDR}'] = explode('/', $netdata['desc']);
  985. $templatedata['{NETWORK}'] = $templatedata['{CIDR}'][0];
  986. $templatedata['{CIDR}'] = $templatedata['{CIDR}'][1];
  987. $templatedata['{ROUTERS}'] = int2ip(ip2int($templatedata['{STARTIP}']) + 1);
  988. $templatedata['{MASK}'] = multinet_cidr2mask($templatedata['{CIDR}']);
  989. $dhcpdata = $alldhcpsubnets[$eachnet['netid']];
  990. if (isset($dhcpdata['confname'])) {
  991. $templatedata['{HOSTS}'] = $dhcpdata['confname'];
  992. // check for override?
  993. if (!empty($dhcpdata['dhcpconfig'])) {
  994. $currentsubtpl = $dhcpdata['dhcpconfig'];
  995. } else {
  996. $currentsubtpl = $subnets_template;
  997. }
  998. $subnets .= multinet_ParseTemplate($currentsubtpl, $templatedata) . "\n";
  999. }
  1000. }
  1001. }
  1002. }
  1003. $globdata['{SUBNETS}'] = $subnets;
  1004. $globdata['{DENYMEMBERS}'] = $membersMacroContent;
  1005. $globdata['{DENYVLANGENMEMBERS}'] = $vlanMembersMacroContent;
  1006. $globdata['{DENYONUMEMBERS}'] = $onuMembersMacroContent;
  1007. $globconf = multinet_ParseTemplate($global_template, $globdata);
  1008. file_write_contents("multinet/dhcpd.conf", $globconf);
  1009. }
  1010. /**
  1011. * Returns array of all available nethosts as id=>nethostdata
  1012. *
  1013. * @return array
  1014. */
  1015. function multinet_nethosts_get_all() {
  1016. $result = array();
  1017. $query = "SELECT * from `nethosts`";
  1018. $all = simple_queryall($query);
  1019. if (!empty($all)) {
  1020. foreach ($all as $io => $each) {
  1021. $result[$each['id']] = $each;
  1022. }
  1023. }
  1024. return ($result);
  1025. }
  1026. /**
  1027. * Performs rebuild of all networks handlers due their type
  1028. *
  1029. * @return void
  1030. */
  1031. function multinet_rebuild_all_handlers() {
  1032. global $ubillingConfig;
  1033. $dhcpEnabledFlag = $ubillingConfig->getAlterParam('DHCP_ENABLED');
  1034. $opt82EnabledFlag = $ubillingConfig->getAlterParam('OPT82_ENABLED');
  1035. $pppEnabledFlag = $ubillingConfig->getAlterParam('PPP_ENABLED');
  1036. $ddnsFlag = $ubillingConfig->getAlterParam('DHCP_DDNS_ENABLED');
  1037. if ($ddnsFlag) {
  1038. $loginIps = zb_UserGetAllIPs();
  1039. $loginIps = array_flip($loginIps); //IP=>login
  1040. $useDdns = true;
  1041. } else {
  1042. $loginIps = array();
  1043. $useDdns = false;
  1044. }
  1045. $allnets = multinet_get_all_networks_assoc(); //all networks basic params
  1046. $allDhcpData = dhcp_get_all_data_assoc(); //all networks dhcpd data
  1047. $allNethosts = multinet_nethosts_get_all(); //all available user nethosts data
  1048. if (!empty($allnets)) {
  1049. foreach ($allnets as $io => $eachnet) {
  1050. switch ($eachnet['nettype']) {
  1051. case 'dhcpstatic':
  1052. if ($dhcpEnabledFlag) {
  1053. if (isset($allDhcpData[$eachnet['id']])) {
  1054. $dhcpdata = $allDhcpData[$eachnet['id']];
  1055. handle_dhcp_rebuild_static($eachnet['id'], @$dhcpdata['confname'], $useDdns, $loginIps, $allNethosts);
  1056. }
  1057. }
  1058. break;
  1059. case 'dhcp82':
  1060. if ($opt82EnabledFlag) {
  1061. if (isset($allDhcpData[$eachnet['id']])) {
  1062. $dhcpdata82 = $allDhcpData[$eachnet['id']];
  1063. handle_dhcp_rebuild_option82($eachnet['id'], $dhcpdata82['confname']);
  1064. }
  1065. }
  1066. break;
  1067. case 'dhcp82_vpu':
  1068. if ($opt82EnabledFlag) {
  1069. if (isset($allDhcpData[$eachnet['id']])) {
  1070. $dhcpdata82_vpu = $allDhcpData[$eachnet['id']];
  1071. handle_dhcp_rebuild_option82_vpu($eachnet['id'], $dhcpdata82_vpu['confname']);
  1072. }
  1073. }
  1074. break;
  1075. case 'dhcp82_bdcom':
  1076. if ($opt82EnabledFlag) {
  1077. if (isset($allDhcpData[$eachnet['id']])) {
  1078. $dhcpdata82_bdcom = $allDhcpData[$eachnet['id']];
  1079. handle_dhcp_rebuild_option82_bdcom($eachnet['id'], $dhcpdata82_bdcom['confname']);
  1080. }
  1081. }
  1082. break;
  1083. case 'dhcp82_zte':
  1084. if ($opt82EnabledFlag) {
  1085. if (isset($allDhcpData[$eachnet['id']])) {
  1086. $dhcpdata82_zte = $allDhcpData[$eachnet['id']];
  1087. handle_dhcp_rebuild_option82_zte($eachnet['id'], $dhcpdata82_zte['confname']);
  1088. }
  1089. }
  1090. break;
  1091. case 'pppstatic':
  1092. if ($pppEnabledFlag) {
  1093. handle_ppp_rebuild_static($eachnet['id']);
  1094. }
  1095. break;
  1096. case 'pppdynamic':
  1097. if ($pppEnabledFlag) {
  1098. handle_ppp_rebuild_dynamic($eachnet['id']);
  1099. }
  1100. break;
  1101. }
  1102. }
  1103. }
  1104. if ($dhcpEnabledFlag or $opt82EnabledFlag) {
  1105. //rebuilding global conf
  1106. multinet_rebuild_globalconf();
  1107. //restarting dhcpd
  1108. multinet_RestartDhcp();
  1109. }
  1110. }
  1111. /**
  1112. * Creates new network host in database
  1113. *
  1114. * @param int $netid
  1115. * @param string $ip
  1116. * @param string $mac
  1117. * @param string $option
  1118. *
  1119. * @return void
  1120. */
  1121. function multinet_add_host($netid, $ip, $mac = 'NULL', $option = 'NULL') {
  1122. $query = "INSERT INTO `nethosts` (`id` ,`ip` ,`mac` ,`netid` ,`option`) VALUES
  1123. (NULL , '" . $ip . "', '" . $mac . "', '" . $netid . "', '" . $option . "');";
  1124. nr_query($query);
  1125. log_register("ADD MultiNetHost `" . $ip . '`');
  1126. }
  1127. /**
  1128. * Changes existing network host MAC address by host IP
  1129. *
  1130. * @param string $ip
  1131. * @param string $newmac
  1132. *
  1133. * @return void
  1134. */
  1135. function multinet_change_mac($ip, $newmac) {
  1136. $newmac = strtolower($newmac);
  1137. $query = "UPDATE `nethosts` SET `mac` = '" . $newmac . "' WHERE `ip` = '" . $ip . "' ;";
  1138. nr_query($query);
  1139. log_register("CHANGE MultiNetHostMac " . $ip . " " . $newmac);
  1140. zb_UserGetAllDataCacheClean();
  1141. }
  1142. /**
  1143. * Extracts all IPs between another two.
  1144. * Preserving broadcasts, net address and first IP for NAS.
  1145. *
  1146. * @param string $first_ip
  1147. * @param string $last_ip
  1148. *
  1149. * @return array
  1150. */
  1151. function multinet_expand_network($first_ip, $last_ip) {
  1152. $filterednet = array();
  1153. $first = ip2int($first_ip);
  1154. $last = ip2int($last_ip);
  1155. for ($i = $first; $i <= $last; $i++) {
  1156. $totalnet[] = int2ip($i);
  1157. }
  1158. if (!empty($totalnet)) {
  1159. foreach ($totalnet as $eachip) {
  1160. if (preg_match("#\.(0|1|255)$#", $eachip)) {
  1161. unset($eachip);
  1162. }
  1163. if (isset($eachip)) {
  1164. $filterednet[] = $eachip;
  1165. }
  1166. }
  1167. }
  1168. return ($filterednet);
  1169. }
  1170. /**
  1171. * Returns all free and unused IP addresses for some network ID
  1172. *
  1173. * @param type $table
  1174. * @param type $field
  1175. * @param type $network_id
  1176. *
  1177. * @return array
  1178. */
  1179. function multinet_get_all_free_ip($table, $field, $network_id) {
  1180. $clear_ips = array();
  1181. $free_ip_pool = array();
  1182. $network_spec = multinet_get_network_params($network_id);
  1183. if (!empty($network_spec)) {
  1184. $first_ip = $network_spec['startip'];
  1185. $last_ip = $network_spec['endip'];
  1186. $full_network_pool = multinet_expand_network($first_ip, $last_ip);
  1187. $current_state_q = "SELECT `" . $field . "` from `" . $table . "` WHERE `netid` = '" . $network_id . "'";
  1188. $all_current_used_ip = simple_queryall($current_state_q);
  1189. if (!empty($all_current_used_ip)) {
  1190. foreach ($all_current_used_ip as $io => $usedip) {
  1191. $clear_ips[] = $usedip[$field];
  1192. }
  1193. $free_ip_pool = array_diff($full_network_pool, $clear_ips);
  1194. } else {
  1195. $free_ip_pool = $full_network_pool;
  1196. }
  1197. }
  1198. return ($free_ip_pool);
  1199. }
  1200. /**
  1201. * Counts free IPs fast for certain network
  1202. *
  1203. * @param int $network_id
  1204. *
  1205. * @return int
  1206. */
  1207. function multinet_get_free_count($network_id) {
  1208. $network_spec = multinet_get_network_params($network_id);
  1209. $desc = $network_spec['desc'];
  1210. $desc_parts = explode("/", $desc);
  1211. $network = $desc_parts[0];
  1212. $cidr = $desc_parts[1];
  1213. $first_ip = ip2long($network_spec['startip']);
  1214. $last_ip = ip2long($network_spec['endip']);
  1215. $count_all = $last_ip - $first_ip;
  1216. $num_hosts = pow(2, 32 - $cidr);
  1217. if ($count_all >= $num_hosts - (3 * ceil($num_hosts / 256))) {
  1218. $count_all = $num_hosts - (3 * ceil($num_hosts / 256));
  1219. }
  1220. $query = "SELECT COUNT(*) as used FROM `nethosts` WHERE `netid`='" . $network_id . "'";
  1221. $count_result = simple_query($query);
  1222. $count_used = $count_result['used'];
  1223. $free_count = $count_all - $count_used;
  1224. return ($free_count);
  1225. }
  1226. /**
  1227. * Returns first free and unused IP for some network ID
  1228. *
  1229. * @param string $table
  1230. * @param string $field
  1231. * @param int $network_id
  1232. *
  1233. * @return string
  1234. */
  1235. function multinet_get_next_freeip($table, $field, $network_id) {
  1236. $all_free_ips = multinet_get_all_free_ip($table, $field, $network_id);
  1237. $temp = array_keys($all_free_ips);
  1238. return (@$all_free_ips[$temp[0]]);
  1239. }
  1240. /**
  1241. * Returns network ID by associated service ID
  1242. *
  1243. * @param int $service_id
  1244. *
  1245. * @return int
  1246. */
  1247. function multinet_get_service_networkid($service_id) {
  1248. $service_id = vf($service_id);
  1249. $query = "SELECT `netid` from `services` WHERE `id`='" . $service_id . "'";
  1250. $service_network = simple_query($query);
  1251. if (!empty($service_network)) {
  1252. $service_network = $service_network['netid'];
  1253. } else {
  1254. $service_network = 0;
  1255. }
  1256. return ($service_network);
  1257. }
  1258. /**
  1259. * Checks is some IP between another two
  1260. *
  1261. * @param string $user_ip
  1262. * @param string $ip_begin
  1263. * @param string $ip_end
  1264. *
  1265. * @return bool
  1266. */
  1267. function multinet_checkIP($user_ip, $ip_begin, $ip_end) {
  1268. return (ip2int($user_ip) >= ip2int($ip_begin) && ip2int($user_ip) <= ip2int($ip_end));
  1269. }
  1270. /**
  1271. * Converts bytes into human-readable values like Kb, Mb, Gb...
  1272. *
  1273. * @param int $fs
  1274. * @param string $traffsize
  1275. *
  1276. * @return string
  1277. */
  1278. function zb_convertSize($fs, $traffsize = 'float') {
  1279. if ($traffsize == 'float') {
  1280. if ($fs >= (1073741824 * 1024))
  1281. $fs = round($fs / (1073741824 * 1024) * 100) / 100 . ' ' . __('Tb');
  1282. elseif ($fs >= 1073741824)
  1283. $fs = round($fs / 1073741824 * 100) / 100 . ' ' . __('Gb');
  1284. elseif ($fs >= 1048576)
  1285. $fs = round($fs / 1048576 * 100) / 100 . ' ' . __('Mb');
  1286. elseif ($fs >= 1024)
  1287. $fs = round($fs / 1024 * 100) / 100 . ' ' . __('Kb');
  1288. else
  1289. $fs = $fs . ' ' . __('b');
  1290. return ($fs);
  1291. }
  1292. if ($traffsize == 'b') {
  1293. return ($fs);
  1294. }
  1295. if ($traffsize == 'Kb') {
  1296. $fs = round($fs / 1024 * 100) / 100 . ' ' . __('Kb');
  1297. return ($fs);
  1298. }
  1299. if ($traffsize == 'Mb') {
  1300. $fs = round($fs / 1048576 * 100) / 100 . ' ' . __('Mb');
  1301. return ($fs);
  1302. }
  1303. if ($traffsize == 'Gb') {
  1304. $fs = round($fs / 1073741824 * 100) / 100 . ' ' . __('Gb');
  1305. return ($fs);
  1306. }
  1307. if ($traffsize == 'Tb') {
  1308. $fs = round($fs / (1073741824 * 1024) * 100) / 100 . ' ' . __('Tb');
  1309. return ($fs);
  1310. }
  1311. }
  1312. /**
  1313. * Converts bytes into human-readable values like Kb, Mb, Gb, configurable via TRAFFSIZE alter option.
  1314. *
  1315. *
  1316. * @global object $ubillingConfig
  1317. *
  1318. * @param int $fs
  1319. *
  1320. * @return string
  1321. */
  1322. function stg_convert_size($fs) {
  1323. global $ubillingConfig;
  1324. $alter_conf = $ubillingConfig->getAlter();
  1325. $traffsize = trim($alter_conf['TRAFFSIZE']);
  1326. return (zb_convertSize($fs, $traffsize));
  1327. }
  1328. /**
  1329. * Convert bytes to human-readable Gb values. Much faster than stg_convert_size()/zb_convertSize
  1330. *
  1331. * @param int $fs
  1332. *
  1333. * @return string
  1334. */
  1335. function zb_TraffToGb($fs) {
  1336. $fs = round($fs / 1073741824, 2) . " Gb";
  1337. return ($fs);
  1338. }
  1339. /**
  1340. * Returns array of available tariff speeds as tariffname=>array(speeddown/speedup)
  1341. *
  1342. * @return array
  1343. */
  1344. function zb_TariffGetAllSpeeds() {
  1345. global $ubillingConfig;
  1346. $query = "SELECT * from `speeds`";
  1347. $allspeeds = simple_queryall($query);
  1348. $result = array();
  1349. if (!empty($allspeeds)) {
  1350. foreach ($allspeeds as $io => $eachspeed) {
  1351. $result[$eachspeed['tariff']]['speeddown'] = $eachspeed['speeddown'];
  1352. $result[$eachspeed['tariff']]['speedup'] = $eachspeed['speedup'];
  1353. if ($ubillingConfig->getAlterParam('BURST_ENABLED')) {
  1354. $result[$eachspeed['tariff']]['burstdownload'] = $eachspeed['burstdownload'];
  1355. $result[$eachspeed['tariff']]['burstupload'] = $eachspeed['burstupload'];
  1356. $result[$eachspeed['tariff']]['bursttimedownload'] = $eachspeed['bursttimedownload'];
  1357. $result[$eachspeed['tariff']]['burstimetupload'] = $eachspeed['burstimetupload'];
  1358. }
  1359. }
  1360. }
  1361. return ($result);
  1362. }
  1363. /**
  1364. * Creates new tariff speed record in database
  1365. *
  1366. * @param type $tariff
  1367. * @param type $speeddown
  1368. * @param type $speedup
  1369. * @param type $burstdownload
  1370. * @param type $burstupload
  1371. * @param type $bursttimedownload
  1372. * @param type $burstimetupload
  1373. *
  1374. * @return void
  1375. */
  1376. function zb_TariffCreateSpeed($tariff, $speeddown, $speedup, $burstdownload = '', $burstupload = '', $bursttimedownload = '', $burstimetupload = '') {
  1377. $tariff = mysql_real_escape_string($tariff);
  1378. $speeddown = vf($speeddown);
  1379. $speedup = vf($speedup);
  1380. if ($speeddown == '') {
  1381. $speeddown = 0;
  1382. }
  1383. if ($speedup == '') {
  1384. $speedup = 0;
  1385. }
  1386. $burstdownload = vf($burstdownload);
  1387. $burstupload = vf($burstupload);
  1388. $bursttimedownload = vf($bursttimedownload);
  1389. $burstimetupload = vf($burstimetupload);
  1390. $query = "INSERT INTO `speeds` (`id` , `tariff` , `speeddown` , `speedup` , `burstdownload` , `burstupload` , `bursttimedownload` , `burstimetupload`) VALUES
  1391. (NULL , '" . $tariff . "', '" . $speeddown . "', '" . $speedup . "', '" . $burstdownload . "', '" . $burstupload . "', '" . $bursttimedownload . "', '" . $burstimetupload . "');";
  1392. nr_query($query);
  1393. log_register('CREATE TariffSpeed `' . $tariff . '` ' . $speeddown . ' ' . $speedup . ' ' . $burstdownload . ' ' . $burstupload . ' ' . $bursttimedownload . ' ' . $burstimetupload);
  1394. }
  1395. /**
  1396. * Deletes tariff speed from database
  1397. *
  1398. * @param string $tariff
  1399. *
  1400. * @return void
  1401. */
  1402. function zb_TariffDeleteSpeed($tariff) {
  1403. $tariff = mysql_real_escape_string($tariff);
  1404. $query = "DELETE from `speeds` where `tariff`='" . $tariff . "'";
  1405. nr_query($query);
  1406. log_register('DELETE TariffSpeed `' . $tariff . '`');
  1407. }
  1408. /**
  1409. * Returns array of tariff-based signup prices as tariff=>price
  1410. *
  1411. * @return array
  1412. */
  1413. function zb_TariffGetAllSignupPrices() {
  1414. $query = "SELECT * FROM `signup_prices_tariffs`";
  1415. $results = simple_queryall($query);
  1416. $return = array();
  1417. if (!empty($results)) {
  1418. foreach ($results as $result) {
  1419. $return[$result['tariff']] = $result['price'];
  1420. }
  1421. }
  1422. return ($return);
  1423. }
  1424. /**
  1425. * Creates new tariff-based signup price in database
  1426. *
  1427. * @param string $tariff
  1428. * @param float $price
  1429. *
  1430. * @return void
  1431. */
  1432. function zb_TariffCreateSignupPrice($tariff, $price) {
  1433. $query = "INSERT INTO `signup_prices_tariffs` (`tariff`, `price`) VALUES ('" . $tariff . "', '" . $price . "')";
  1434. nr_query($query);
  1435. log_register('CREATE TariffSignupPrice ' . $tariff . ' ' . $price);
  1436. }
  1437. /**
  1438. * Deletes tariff-based signup price from database
  1439. *
  1440. * @param string $tariff
  1441. *
  1442. * @return void
  1443. */
  1444. function zb_TariffDeleteSignupPrice($tariff) {
  1445. $query = "DELETE FROM `signup_prices_tariffs` WHERE `tariff` = '" . $tariff . "'";
  1446. nr_query($query);
  1447. log_register('DELETE TariffSignupPrice ' . $tariff);
  1448. }
  1449. /**
  1450. * Returns network host MAC address by its IP
  1451. *
  1452. * @param string $ip
  1453. *
  1454. * @return string
  1455. */
  1456. function zb_MultinetGetMAC($ip) {
  1457. $query = "SELECT `mac` from `nethosts` WHERE `ip`='" . $ip . "'";
  1458. $result = simple_query($query);
  1459. $result = $result['mac'];
  1460. return ($result);
  1461. }
  1462. /**
  1463. * Returns full nethost data by its IP
  1464. *
  1465. * @param string $ip
  1466. *
  1467. * @return array
  1468. */
  1469. function zb_MultinetGetNethostData($ip) {
  1470. $query = "SELECT * from `nethosts` WHERE `ip`='" . $ip . "'";
  1471. $result = simple_queryall($query);
  1472. return ($result);
  1473. }
  1474. /**
  1475. * Returns user IP address by its login
  1476. *
  1477. * @param string $login
  1478. *
  1479. * @return string
  1480. */
  1481. function zb_UserGetIP($login) {
  1482. $userdata = zb_UserGetStargazerData($login);
  1483. $userip = $userdata['IP'];
  1484. return ($userip);
  1485. }
  1486. /**
  1487. * Returns user login by it's IP address
  1488. *
  1489. * @param $ip
  1490. *
  1491. * @return array|string
  1492. */
  1493. function zb_UserGetLoginByIp($ip) {
  1494. $result = '';
  1495. if (!empty($ip)) {
  1496. $query = "SELECT `login` from `users` where `IP`='" . $ip . "'";
  1497. $queryResult = simple_query($query);
  1498. if (!empty($queryResult['login'])) {
  1499. $result = $queryResult['login'];
  1500. }
  1501. }
  1502. return ($result);
  1503. }
  1504. /**
  1505. * Returns array of all available traffic directions
  1506. *
  1507. * @return array
  1508. */
  1509. function zb_DirectionsGetAll() {
  1510. $query = "SELECT * from `directions`";
  1511. $allrules = simple_queryall($query);
  1512. return ($allrules);
  1513. }
  1514. /**
  1515. * Deletes existing traffic direction from database
  1516. *
  1517. * @param int $directionid
  1518. *
  1519. * @return void
  1520. */
  1521. function zb_DirectionDelete($directionid) {
  1522. $directionid = vf($directionid, 3);
  1523. $query = "DELETE FROM `directions` WHERE `id`='" . $directionid . "'";
  1524. nr_query($query);
  1525. log_register('DELETE TrafficClass [' . $directionid . ']');
  1526. rcms_redirect("?module=rules");
  1527. }
  1528. /**
  1529. * Returns traffic direction data
  1530. *
  1531. * @param int $directionid
  1532. *
  1533. * @return array
  1534. */
  1535. function zb_DirectionGetData($directionid) {
  1536. $directionid = vf($directionid, 3);
  1537. $query = "SELECT * from `directions` WHERE `id`='" . $directionid . "'";
  1538. $data = simple_query($query);
  1539. return ($data);
  1540. }
  1541. /**
  1542. * Creates new traffic direction in database
  1543. *
  1544. * @param int $rulenumber
  1545. * @param string $rulename
  1546. *
  1547. * @return void
  1548. */
  1549. function zb_DirectionAdd($rulenumber, $rulename) {
  1550. $rulenumber = vf($rulenumber);
  1551. $rulename = mysql_real_escape_string($rulename);
  1552. $query = "INSERT INTO `directions` (`id` , `rulenumber` , `rulename`) VALUES
  1553. (NULL , '" . $rulenumber . "', '" . $rulename . "');";
  1554. nr_query($query);
  1555. log_register("ADD TrafficClass `" . $rulenumber . '` `' . $rulename . '`');
  1556. }
  1557. /**
  1558. * Creates new NAS in database
  1559. *
  1560. * @param int $netid
  1561. * @param string $nasip
  1562. * @param string $nasname
  1563. * @param string $nastype
  1564. * @param string $bandw
  1565. *
  1566. * @return void
  1567. */
  1568. function zb_NasAdd($netid, $nasip, $nasname, $nastype, $bandw) {
  1569. $netid = vf($netid, 3);
  1570. $nasname = mysql_real_escape_string($nasname);
  1571. $nasname = trim($nasname);
  1572. $nastype = vf($nastype);
  1573. $bandw = trim($bandw);
  1574. $bandw = mysql_real_escape_string($bandw);
  1575. $nasip = mysql_real_escape_string($nasip);
  1576. $query = "INSERT INTO `nas` (`id` ,`netid` , `nasip` , `nasname` , `nastype` , `bandw`) VALUES
  1577. (NULL , '" . $netid . "', '" . $nasip . "', '" . $nasname . "', '" . $nastype . "', '" . $bandw . "' );";
  1578. nr_query($query);
  1579. $newId = simple_get_lastid('nas');
  1580. log_register('NAS ADD [' . $newId . '] `' . $nasip . '`');
  1581. }
  1582. /**
  1583. * Updates existing NAS parameters in database
  1584. *
  1585. * @param int $nasid
  1586. * @param string $nastype
  1587. * @param string $nasip
  1588. * @param string $nasname
  1589. * @param string $nasbwdurl
  1590. * @param int $netid
  1591. *
  1592. * @return void
  1593. */
  1594. function zb_NasUpdateParams($nasid, $nastype, $nasip, $nasname, $nasbwdurl, $netid) {
  1595. $nasid = ubRouting::filters($nasid, 'int');
  1596. $nastype = ubRouting::filters($nastype, 'mres');
  1597. $nasip = ubRouting::filters($nasip, 'mres');
  1598. $nasname = ubRouting::filters($nasname, 'mres');
  1599. $nasname = trim($nasname);
  1600. $nasbwdurl = trim(ubRouting::filters($nasbwdurl, 'mres'));
  1601. $netid = ubRouting::filters($netid, 'int');
  1602. $targetnas = "WHERE `id` = '" . $nasid . "'";
  1603. simple_update_field('nas', 'nastype', $nastype, $targetnas);
  1604. simple_update_field('nas', 'nasip', $nasip, $targetnas);
  1605. simple_update_field('nas', 'nasname', $nasname, $targetnas);
  1606. simple_update_field('nas', 'bandw', $nasbwdurl, $targetnas);
  1607. simple_update_field('nas', 'netid', $netid, $targetnas);
  1608. log_register('NAS EDIT [' . $nasid . '] `' . $nasip . '`');
  1609. }
  1610. /**
  1611. * Returns all available NAS data
  1612. *
  1613. * @return array
  1614. */
  1615. function zb_NasGetAllData() {
  1616. $query = "SELECT * from `nas`";
  1617. $allnas = simple_queryall($query);
  1618. return ($allnas);
  1619. }
  1620. /**
  1621. * Returns some existing NAS parameters
  1622. *
  1623. * @param int $nasid
  1624. *
  1625. * @return array
  1626. */
  1627. function zb_NasGetData($nasid) {
  1628. $nasid = vf($nasid, 3);
  1629. $query = "SELECT * from `nas` WHERE `id`='" . $nasid . "'";
  1630. $result = simple_query($query);
  1631. return ($result);
  1632. }
  1633. /**
  1634. * Gets NAS IP-address, using its id
  1635. *
  1636. * @param int $nasid
  1637. *
  1638. * @return string
  1639. */
  1640. function zb_NasGetIpById($nasid) {
  1641. $nasid = vf($nasid);
  1642. $query = "SELECT `nasip` FROM `nas` WHERE `id` = '" . $nasid . "'";
  1643. $result = simple_query($query);
  1644. return ($result['nasip']);
  1645. }
  1646. /**
  1647. * Decodes and unserializes data from base64 encoding
  1648. *
  1649. * @param int $nasid NAS'es id to update options
  1650. * @param array $data Options
  1651. *
  1652. * @return array Options
  1653. */
  1654. function zb_NasOptionsGet($nasid) {
  1655. $result = array();
  1656. if (!empty($nasid)) {
  1657. $query = "SELECT `options` FROM `nas` WHERE `id` = " . $nasid . ";";
  1658. $result = simple_queryall($query);
  1659. if (!empty($result)) {
  1660. foreach ($result as $data) {
  1661. $decoded = base64_decode($data['options']);
  1662. $result = unserialize($decoded);
  1663. }
  1664. }
  1665. }
  1666. return $result;
  1667. }
  1668. /**
  1669. * Deletes NAS from database
  1670. *
  1671. * @param int $nasid
  1672. *
  1673. * @return void
  1674. */
  1675. function zb_NasDelete($nasid) {
  1676. $nasid = vf($nasid, 3);
  1677. $query = "DELETE from `nas` WHERE `id`='" . $nasid . "'";
  1678. nr_query($query);
  1679. log_register('NAS DELETE [' . $nasid . ']');
  1680. }
  1681. /**
  1682. * Saves rscriptd NAS servers config and sends HUP signal to stargazer
  1683. *
  1684. * @return void
  1685. */
  1686. function zb_NasConfigSave() {
  1687. $ub_conf = rcms_parse_ini_file(CONFIG_PATH . "billing.ini");
  1688. $query = "SELECT * from `nas` WHERE `nastype`='rscriptd'";
  1689. $result = '';
  1690. $allnas = simple_queryall($query);
  1691. if (!empty($allnas)) {
  1692. foreach ($allnas as $io => $eachnas) {
  1693. $net_q = multinet_get_network_params($eachnas['netid']);
  1694. $net_cidr = $net_q['desc'];
  1695. $result .= $net_cidr . ' ' . $eachnas['nasip'] . "\n";
  1696. }
  1697. }
  1698. file_put_contents('remote_nas.conf', $result);
  1699. if ($ub_conf['STGNASHUP']) {
  1700. $sig_command = $ub_conf['SUDO'] . ' ' . $ub_conf['KILL'] . ' -1' . ' `' . $ub_conf['CAT'] . ' ' . $ub_conf['STGPID'] . '`';
  1701. shell_exec($sig_command);
  1702. log_register("SIGHUP STG ");
  1703. }
  1704. }
  1705. /**
  1706. * Restarts ISC-DHCPD server
  1707. *
  1708. * @return void
  1709. */
  1710. function multinet_RestartDhcp() {
  1711. global $ubillingConfig;
  1712. $altCfg = $ubillingConfig->getAlter();
  1713. if (@$altCfg['DHCP_ENABLED']) {
  1714. $config = $ubillingConfig->getBilling();
  1715. $sudo = $config['SUDO'];
  1716. $dhcpd = $config['RC_DHCPD'];
  1717. $command = $sudo . ' ' . $dhcpd . ' restart';
  1718. shell_exec($command);
  1719. log_register('RESTART DHCPD');
  1720. }
  1721. }
  1722. /**
  1723. * Returns NAS id by associated network ID
  1724. *
  1725. * @param int $netid
  1726. *
  1727. * @return int
  1728. */
  1729. function zb_NasGetByNet($netid) {
  1730. $netid = vf($netid, 3);
  1731. $query = "SELECT `id` from `nas` WHERE `netid`='" . $netid . "'";
  1732. $nasid = simple_query($query);
  1733. $nasid = @$nasid['id'];
  1734. return ($nasid);
  1735. }
  1736. /**
  1737. * Returns network ID by some IP address
  1738. *
  1739. * @param string $ip
  1740. *
  1741. * @return int
  1742. */
  1743. function zb_NetworkGetByIp($ip) {
  1744. $allnets = multinet_get_all_networks();
  1745. if (!empty($allnets)) {
  1746. foreach ($allnets as $io => $eachnet) {
  1747. $completenet = multinet_checkIP($ip, $eachnet['startip'], $eachnet['endip']);
  1748. if ($completenet) {
  1749. $result = $eachnet['id'];
  1750. break;
  1751. } else {
  1752. $result = false;
  1753. }
  1754. }
  1755. }
  1756. return ($result);
  1757. }
  1758. /**
  1759. * Gets the Bandwidthd URL by user's IP address from database
  1760. *
  1761. * @param string $ip User's IP address
  1762. *
  1763. * @return string Bandwidthd URL
  1764. */
  1765. function zb_BandwidthdGetUrl($ip) {
  1766. $netid = zb_NetworkGetByIp($ip);
  1767. $nasid = zb_NasGetByNet($netid);
  1768. $nasdata = zb_NasGetData($nasid);
  1769. $bandwidthd_url = @$nasdata['bandw'];
  1770. if (!empty($bandwidthd_url)) {
  1771. return $bandwidthd_url;
  1772. } else
  1773. return false;
  1774. }
  1775. /**
  1776. * Returns exploded array of some multi-lined strings
  1777. *
  1778. * @param string $data
  1779. *
  1780. * @return array
  1781. */
  1782. function explodeRows($data) {
  1783. $result = explode("\n", $data);
  1784. return ($result);
  1785. }
  1786. /**
  1787. * Parses MAC addresses from a given source path and returns they as unique MAC array idx=>MAC
  1788. *
  1789. * @param string $source The path to the source file to read from.
  1790. * @param int $lines The number of lines to read from the source file.
  1791. * @param string $customLeaseMark An optional custom lease mark to use for filtering lines.
  1792. *
  1793. * @return array
  1794. */
  1795. function zb_MacParseSource($source, $lines = 200, $customLeaseMark = '') {
  1796. global $ubillingConfig;
  1797. $result = array();
  1798. $allMacs = array();
  1799. $source = trim($source);
  1800. $extendFlag = ($ubillingConfig->getAlterParam('NMLEASES_EXTEND')) ? true : false;
  1801. $leasemark = $ubillingConfig->getAlterParam('NMLEASEMARK');
  1802. if ($customLeaseMark) {
  1803. $leasemark = $customLeaseMark;
  1804. }
  1805. $billCfg = $ubillingConfig->getBilling();
  1806. $sudo = $billCfg['SUDO'];
  1807. $cat = $billCfg['CAT'];
  1808. $grep = $billCfg['GREP'];
  1809. $tail = $billCfg['TAIL'];
  1810. $filter = '';
  1811. if (!empty($leasemark)) {
  1812. $filter .= ' | ' . $grep . ' "' . $leasemark . '" ';
  1813. }
  1814. $command = $sudo . ' ' . $cat . ' ' . $source . $filter . ' | ' . $tail . ' -n ' . $lines;
  1815. $rawdata = shell_exec($command);
  1816. // Aandene har begynt aa vise seg for meg
  1817. // Stryk katten mot haarene
  1818. // Salt i saaret
  1819. // Svette
  1820. if (!empty($source)) {
  1821. if (!empty($rawdata)) {
  1822. $cleardata = exploderows($rawdata);
  1823. foreach ($cleardata as $eachline) {
  1824. preg_match('/[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}/i', $eachline, $matches);
  1825. if (!empty($matches)) {
  1826. $allMacs[] = $matches[0];
  1827. }
  1828. if ($extendFlag) {
  1829. $eachline = preg_replace('/([a-f0-9]{2})(?![\s\]\/])([\.\:\-]?)/', '\1:', $eachline);
  1830. preg_match('/[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}/i', $eachline, $matches);
  1831. if (!empty($matches[0])) {
  1832. $allMacs[] = $matches[0];
  1833. }
  1834. }
  1835. }
  1836. $result = array_unique($allMacs);
  1837. }
  1838. }
  1839. return ($result);
  1840. }
  1841. /**
  1842. * Returns new unknown MAC addresses list parsed from NMLEASES and NMSOURCES_ADDITIONAL sources.
  1843. *
  1844. * @global object $ubillingConfig
  1845. *
  1846. * @return string
  1847. */
  1848. function zb_NewMacShow() {
  1849. global $ubillingConfig;
  1850. $result = '';
  1851. $allUsedMacs = zb_getAllUsedMac();
  1852. $allMacs = array();
  1853. $unknownMacCount = 0;
  1854. $lineLimit = ($ubillingConfig->getAlterParam('NMLOOKUP_DEPTH')) ? $ubillingConfig->getAlterParam('NMLOOKUP_DEPTH') : 200;
  1855. $leases = $ubillingConfig->getAlterParam('NMLEASES');
  1856. $additionalSources = $ubillingConfig->getAlterParam('NMSOURCES_ADDITIONAL');
  1857. $reverseFlag = ($ubillingConfig->getAlterParam('NMREVERSE')) ? true : false;
  1858. $macvenFlag = ($ubillingConfig->getAlterParam('MACVEN_ENABLED')) ? true : false;
  1859. $additionalMark = ($ubillingConfig->getAlterParam('NMLEASEMARK_ADDITIONAL')) ? $ubillingConfig->getAlterParam('NMLEASEMARK_ADDITIONAL') : '';
  1860. if ($macvenFlag) {
  1861. $result .= wf_AjaxLoader();
  1862. //additional macven rights check
  1863. if (!cfr('MACVEN')) {
  1864. $macvenFlag = false;
  1865. }
  1866. }
  1867. //parsing new MAC sources
  1868. if (!empty($leases)) {
  1869. $allMacs += zb_MacParseSource($leases, $lineLimit);
  1870. }
  1871. //and optional additional sources
  1872. if (!empty($additionalSources)) {
  1873. $additionalSources = explode(',', $additionalSources);
  1874. if (!empty($additionalSources)) {
  1875. foreach ($additionalSources as $io => $eachAdditionalSource) {
  1876. $supSourceMacs = zb_MacParseSource($eachAdditionalSource, $lineLimit, $additionalMark);
  1877. $allMacs = array_merge($allMacs, $supSourceMacs);
  1878. }
  1879. }
  1880. }
  1881. //fdb cache preprocessing
  1882. $fdbData_raw = rcms_scandir('./exports/', '*_fdb');
  1883. if (!empty($fdbData_raw)) {
  1884. $fdbArr = sn_SnmpParseFdbCacheArray($fdbData_raw);
  1885. $fdbColumn = true;
  1886. } else {
  1887. $fdbArr = array();
  1888. $fdbColumn = false;
  1889. }
  1890. $cells = wf_TableCell(__('MAC'));
  1891. if ($fdbColumn) {
  1892. $cells .= wf_TableCell(__('Switch'));
  1893. }
  1894. if ($macvenFlag) {
  1895. $cells .= wf_TableCell(__('Manufacturer'));
  1896. }
  1897. $rows = wf_TableRow($cells, 'row1');
  1898. if (!empty($allMacs)) {
  1899. if ($reverseFlag) {
  1900. //revert array due usability reasons
  1901. $allMacs = array_reverse($allMacs);
  1902. }
  1903. foreach ($allMacs as $io => $eachmac) {
  1904. if (zb_checkMacFree($eachmac, $allUsedMacs)) {
  1905. $cells = wf_TableCell(@$eachmac);
  1906. if (!empty($fdbColumn)) {
  1907. $cells .= wf_TableCell(sn_SnmpParseFdbExtract(@$fdbArr[$eachmac]));
  1908. }
  1909. if ($macvenFlag) {
  1910. $containerName = 'NMRSMCNT_' . zb_rand_string(8);
  1911. $lookupVendorLink = wf_AjaxLink('?module=macvendor&mac=' . @$eachmac . '&raw=true', wf_img('skins/macven.gif', __('Device vendor')), $containerName, false, '');
  1912. $lookupVendorLink .= wf_tag('span', false, '', 'id="' . $containerName . '"') . '' . wf_tag('span', true);
  1913. $cells .= wf_TableCell($lookupVendorLink, '350');
  1914. }
  1915. $rows .= wf_TableRow($cells, 'row5');
  1916. $unknownMacCount++;
  1917. }
  1918. }
  1919. }
  1920. if ($unknownMacCount > 0) {
  1921. $result .= wf_TableBody($rows, '100%', '0', 'sortable');
  1922. } else {
  1923. $messages = new UbillingMessageHelper();
  1924. $result .= $messages->getStyledMessage(__('Nothing to show'), 'info');
  1925. $result .= wf_delimiter();
  1926. }
  1927. return ($result);
  1928. }
  1929. /**
  1930. * Checks is MAC unused by someone?
  1931. *
  1932. * @param string $mac
  1933. *
  1934. * @return bool
  1935. */
  1936. function multinet_mac_free($mac) {
  1937. $query = "SELECT `id` from `nethosts` WHERE `mac`='" . $mac . "'";
  1938. $res = simple_query($query);
  1939. if (!empty($res)) {
  1940. return (false);
  1941. } else {
  1942. return (true);
  1943. }
  1944. }
  1945. /**
  1946. * Returns all used MAC addresses from database
  1947. *
  1948. * @return array
  1949. */
  1950. function zb_getAllUsedMac() {
  1951. $query = "SELECT `ip`,`mac` from `nethosts`";
  1952. $all = simple_queryall($query);
  1953. $result = array();
  1954. if (!empty($all)) {
  1955. foreach ($all as $io => $each) {
  1956. $result[strtolower($each['mac'])] = $each['ip'];
  1957. }
  1958. }
  1959. return ($result);
  1960. }
  1961. /**
  1962. * Checks is MAC unused by full list of used MACs
  1963. *
  1964. * @param string $mac
  1965. * @param array $allused
  1966. *
  1967. * @return bool
  1968. */
  1969. function zb_checkMacFree($mac, $allused) {
  1970. $mac = strtolower($mac);
  1971. if (isset($allused[$mac])) {
  1972. return (false);
  1973. } else {
  1974. return (true);
  1975. }
  1976. }
  1977. /**
  1978. * Check mac for valid format
  1979. *
  1980. * @param string $mac
  1981. *
  1982. * @return bool
  1983. */
  1984. function check_mac_format($mac) {
  1985. $mask = '/^[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}$/i';
  1986. //really shitty mac
  1987. if ($mac == '00:00:00:00:00:00') {
  1988. return (false);
  1989. }
  1990. if (preg_match($mask, $mac)) {
  1991. return (true);
  1992. } else {
  1993. return (false);
  1994. }
  1995. }
  1996. /**
  1997. * Returns list of all network hosts networks as IPs => netid
  1998. *
  1999. * @return array
  2000. */
  2001. function zb_UserGetNetidsAll() {
  2002. $query = "SELECT * from `nethosts`";
  2003. $result = array();
  2004. $allhosts = simple_queryall($query);
  2005. if (!empty($allhosts)) {
  2006. foreach ($allhosts as $io => $eachhost) {
  2007. $result[$eachhost['ip']] = $eachhost['netid'];
  2008. }
  2009. }
  2010. return ($result);
  2011. }
  2012. /**
  2013. * Sends SIGHUP signal to stargazer
  2014. *
  2015. * @return void
  2016. */
  2017. function zb_StargazerSIGHUP() {
  2018. $ub_conf = rcms_parse_ini_file(CONFIG_PATH . "billing.ini");
  2019. if ($ub_conf['STGNASHUP']) {
  2020. $sig_command = $ub_conf['SUDO'] . ' ' . $ub_conf['KILL'] . ' -1' . ' `' . $ub_conf['CAT'] . ' ' . $ub_conf['STGPID'] . '`';
  2021. shell_exec($sig_command);
  2022. log_register("SIGHUP STG");
  2023. }
  2024. }
  2025. /**
  2026. * Extracts IP address from string
  2027. *
  2028. * @param string $data
  2029. *
  2030. * @return string
  2031. */
  2032. function zb_ExtractIpAddress($data) {
  2033. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $data, $matches);
  2034. if (!empty($matches[0])) {
  2035. return ($matches[0]);
  2036. } else {
  2037. return (false);
  2038. }
  2039. }
  2040. /**
  2041. * Extracts MAC address from string
  2042. *
  2043. * @param string $data
  2044. *
  2045. * @return string
  2046. */
  2047. function zb_ExtractMacAddress($data) {
  2048. $result = '';
  2049. preg_match('/[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}/i', $data, $matches);
  2050. if (!empty($matches)) {
  2051. $result = $matches[0];
  2052. }
  2053. return ($result);
  2054. }
  2055. /**
  2056. * Converts IP to integer value
  2057. *
  2058. * @param string $src
  2059. *
  2060. * @return int
  2061. */
  2062. function ip2int($src) {
  2063. $t = explode('.', $src);
  2064. return count($t) != 4 ? 0 : 256 * (256 * ((float) $t[0] * 256 + (float) $t[1]) + (float) $t[2]) + (float) $t[3];
  2065. }
  2066. /**
  2067. * Converts integer into IP
  2068. *
  2069. * @param int $src
  2070. *
  2071. * @return string
  2072. */
  2073. function int2ip($src) {
  2074. $s1 = (int) ($src / 256);
  2075. $i1 = $src - 256 * $s1;
  2076. $src = (int) ($s1 / 256);
  2077. $i2 = $s1 - 256 * $src;
  2078. $s1 = (int) ($src / 256);
  2079. return sprintf('%d.%d.%d.%d', $s1, $src - 256 * $s1, $i2, $i1);
  2080. }
  2081. /**
  2082. * Removes some separator from MAC address
  2083. *
  2084. * @param string $mac
  2085. * @param string $separator
  2086. *
  2087. * @return string
  2088. */
  2089. function RemoveMacAddressSeparator($mac, $separator = array(':', '-', '.')) {
  2090. return str_replace($separator, '', $mac);
  2091. }
  2092. /**
  2093. * Adds some MAC separator into MAC
  2094. *
  2095. * @param string $mac
  2096. * @param string $separator
  2097. *
  2098. * @return string
  2099. */
  2100. function AddMacSeparator($mac, $separator = ':') {
  2101. return join($separator, str_split($mac, 2));
  2102. }
  2103. /**
  2104. * Yet another MAC format validator. Use check_mac_format() in real life.
  2105. *
  2106. * @param string $mac
  2107. *
  2108. * @return bool
  2109. */
  2110. function IsMacValid($mac) {
  2111. return (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $mac) == 1);
  2112. }
  2113. /**
  2114. * And Another MAC format validator. I rly dont know what for. Use check_mac_format() in real life.
  2115. *
  2116. * @param string $mac
  2117. *
  2118. * @return bool
  2119. */
  2120. function IsMacAddressValid($mac) {
  2121. $validator = new Zend_Validate_Regex('/([a-fA-F0-9]{2}[:|\-]?){6}/');
  2122. return $validator->isValid($mac);
  2123. }
  2124. /**
  2125. * Gets Zabbix graphs data for NASes from cache
  2126. *
  2127. * @return string
  2128. */
  2129. function getCachedZabbixNASGraphIDs() {
  2130. global $ubillingConfig;
  2131. $result = '';
  2132. $cache = new UbillingCache();
  2133. $cacheTime = ($ubillingConfig->getAlterParam('ZABBIX_GRAPHSIDS_CACHE_LIFETIME')) ? $ubillingConfig->getAlterParam('ZABBIX_GRAPHSIDS_CACHE_LIFETIME') : 1800;
  2134. $result = $cache->getCallback(
  2135. 'ZABBIX_GRAPHS_IDS',
  2136. function () {
  2137. return (getZabbixNASGraphIDs());
  2138. },
  2139. $cacheTime
  2140. );
  2141. return ($result);
  2142. }
  2143. /**
  2144. * Gets Zabbix graphs data for NASes
  2145. *
  2146. * @return array
  2147. */
  2148. function getZabbixNASGraphIDs() {
  2149. $zbx = new ZabbixAPI();
  2150. $allNAS = zb_NasGetAllData();
  2151. $allNASGraphs = array();
  2152. $zbxAuthToken = $zbx->getAuthToken();
  2153. if (!empty($allNAS) and !empty($zbxAuthToken)) {
  2154. foreach ($allNAS as $eachNAS) {
  2155. $reqParams = array('filter' => array('ip' => $eachNAS['nasip']));
  2156. $zbxNASData = json_decode($zbx->runQuery('host.get', $reqParams), true);
  2157. if (!empty($zbxNASData['result'])) {
  2158. $zbxNASHostID = $zbxNASData['result'][0]['hostid'];
  2159. $reqParams = array('filter' => array('hostid' => $zbxNASHostID));
  2160. $zbxNASGraphs = json_decode($zbx->runQuery('graph.get', $reqParams), true);
  2161. if (!empty($zbxNASGraphs['result'])) {
  2162. $allNASGraphs[$eachNAS['nasip']] = $zbxNASGraphs['result'];
  2163. }
  2164. }
  2165. }
  2166. }
  2167. return ($allNASGraphs);
  2168. }
  2169. /**
  2170. * Generates array with links to user's traffic graphs
  2171. *
  2172. * @param $userIP
  2173. * @param $fieldToSearch
  2174. * @param $dataToSearch
  2175. * @param array $zbxAllGraphs
  2176. * @return array
  2177. */
  2178. function getZabbixUserGraphLinks($userIP, $fieldToSearch, $dataToSearch, $zbxAllGraphs = array(), $zbxExtended = false) {
  2179. if (empty($zbxAllGraphs)) {
  2180. $allGraphs = getCachedZabbixNASGraphIDs();
  2181. } else {
  2182. $allGraphs = $zbxAllGraphs;
  2183. }
  2184. $bandwidthd_url = rtrim(zb_BandwidthdGetUrl($userIP), '/') . '/';
  2185. $netid = zb_NetworkGetByIp($userIP);
  2186. $nasid = zb_NasGetByNet($netid);
  2187. $nasdata = zb_NasGetData($nasid);
  2188. $graphURL = array();
  2189. $graphID = '';
  2190. if (!empty($allGraphs) and isset($allGraphs[$nasdata['nasip']])) {
  2191. $allNASGraphs = $allGraphs[$nasdata['nasip']];
  2192. foreach ($allNASGraphs as $eachGraph) {
  2193. $searchStr = $eachGraph[$fieldToSearch];
  2194. if (stripos($searchStr, $dataToSearch) !== false) {
  2195. $graphID = $eachGraph['graphid'];
  2196. break;
  2197. }
  2198. }
  2199. }
  2200. $graphURL['dayr'] = $bandwidthd_url . 'chart2.php?graphid=' . $graphID . '&period=86400';
  2201. $graphURL['days'] = null;
  2202. $graphURL['weekr'] = $bandwidthd_url . 'chart2.php?graphid=' . $graphID . '&period=604800';
  2203. $graphURL['weeks'] = null;
  2204. $graphURL['monthr'] = $bandwidthd_url . 'chart2.php?graphid=' . $graphID . '&period=2592000';
  2205. $graphURL['months'] = null;
  2206. $graphURL['yearr'] = $bandwidthd_url . 'chart2.php?graphid=' . $graphID . '&period=31536000';
  2207. $graphURL['years'] = null;
  2208. $graphURL['5mins'] = $bandwidthd_url . 'chart2.php?graphid=' . $graphID . '&period=300';
  2209. $graphURL['zbxlink'] = $bandwidthd_url . 'charts.php?graphid=' . $graphID . '&fullscreen=0';
  2210. $graphURL['zbxexten'] = $zbxExtended;
  2211. return ($graphURL);
  2212. }
  2213. /**
  2214. * Gets Zabbix problems and actions by problems
  2215. *
  2216. * @return array
  2217. */
  2218. function getZabbixProblems($switchIP) {
  2219. global $ubillingConfig;
  2220. $zbx = new ZabbixAPI();
  2221. $zbxAuthToken = $zbx->getAuthToken();
  2222. $problemActions = array();
  2223. $switchIP = trim($switchIP);
  2224. if (!empty($switchIP) and !empty($zbxAuthToken)) {
  2225. /* Selectd problem level severities
  2226. Possible values:
  2227. 0 - not classified;
  2228. 1 - informational;
  2229. 2 - warning;
  2230. 3 - medium;
  2231. 4 - high;
  2232. 5 - emergency.
  2233. */
  2234. if ($ubillingConfig->getAlterParam('ZABBIX_PROBLEM_SEVERITIES')) {
  2235. $severities = explode(',', $ubillingConfig->getAlterParam('ZABBIX_PROBLEM_SEVERITIES'));
  2236. } else {
  2237. $severities = array('0', '1', '2', '3', '4', '5');
  2238. }
  2239. $reqParams = array('filter' => array('ip' => $switchIP));
  2240. $zbxHostData = json_decode($zbx->runQuery('host.get', $reqParams), true);
  2241. if (!empty($zbxHostData['result'])) {
  2242. $zbxHostID = $zbxHostData['result'][0]['hostid'];
  2243. $reqParams = array('hostids' => $zbxHostID, 'severities' => $severities, "selectAcknowledges" => "extend");
  2244. $zbxProblemActions = json_decode($zbx->runQuery('problem.get', $reqParams), true);
  2245. if (!empty($zbxProblemActions['result'])) {
  2246. $problemActions = $zbxProblemActions['result'];
  2247. }
  2248. }
  2249. }
  2250. return ($problemActions);
  2251. }
  2252. /**
  2253. * Converts string IPv4 address/netmask to a HEX representation:
  2254. * 192.168.1.1 -> c0a80101
  2255. * $upperCase keep in mind it won't make HEX prefix to upper case, like '0x' -> '0X'
  2256. * $dotSeparated makes something like: 192.168.1.1 -> c0.a8.01.01
  2257. * $hexPrefix makes something like: 192.168.1.1 -> 0xc0a80101
  2258. *
  2259. * @param string $ip
  2260. * @param bool $upperCase
  2261. * @param bool $dotSeparated
  2262. * @param bool $hexPrefix
  2263. *
  2264. * @return string
  2265. */
  2266. function multinet_ip2hex($ip, $upperCase = false, $dotSeparated = false, $hexPrefix = false) {
  2267. $hexIP = '';
  2268. if (!empty($ip)) {
  2269. if ($ip == '0.0.0.0' and $dotSeparated) {
  2270. $hexIP = $ip;
  2271. } else {
  2272. $hexIP = dechex(ip2long($ip));
  2273. if ($dotSeparated) {
  2274. $hexIP = trim(chunk_split($hexIP, 2, '.'), '.');
  2275. }
  2276. if ($upperCase) {
  2277. $hexIP = strtoupper($hexIP);
  2278. }
  2279. }
  2280. if ($hexPrefix) {
  2281. $hexIP = '0x' . $hexIP;
  2282. }
  2283. }
  2284. return ($hexIP);
  2285. }
  2286. /**
  2287. * Tries to get network CIDR from it's description for a given network ID
  2288. *
  2289. * @param $netID
  2290. *
  2291. * @return string
  2292. */
  2293. function multinet_get_network_cidr_from_descr($netID) {
  2294. $networkData = multinet_get_network_params($netID);
  2295. $networkCIDR = (!empty($networkData['desc']) and ispos($networkData['desc'], '/')) ? substr($networkData['desc'], -2) : '';
  2296. return ($networkCIDR);
  2297. }
  2298. /**
  2299. * Simply gathers some network-essential info about user, like netID and NAS data
  2300. *
  2301. * @param $login
  2302. *
  2303. * @return array
  2304. */
  2305. function getNASInfoByLogin($login) {
  2306. $tQuery = "SELECT `login`, `ip`, `tNases`.`netid`, `tNases`.`nasip`, `tNases`.`nastype`, `tNases`.`options`
  2307. FROM `users`
  2308. LEFT JOIN
  2309. (SELECT `nethosts`.`netid`, `nethosts`.`ip`, `nas`.`netid` AS `nas_netid`, `nas`.`nasip`, `nas`.`nastype`, `nas`.`options`
  2310. FROM `nethosts`
  2311. LEFT JOIN `nas` ON `nas`.`netid` = `nethosts`.`netid`) AS tNases USING(`ip`)
  2312. WHERE `users`.`login` = '" . $login . "'";
  2313. $tQueryResult = simple_query($tQuery);
  2314. return ($tQueryResult);
  2315. }
  2316. /**
  2317. * Converts MAC from it's DEC representation back to HEX, like
  2318. * 32.87.175.9.99.125 => 20:57:AF:09:63:7D
  2319. * or
  2320. * 52:45:13:39:180:117 => 34:2D:0D:27:B4:75
  2321. *
  2322. * @param string $decMAC
  2323. * @param string $inSeparator
  2324. * @param string $outSeparator
  2325. * @param false $reversed - set to true if DEC MAC is reversed
  2326. *
  2327. * @return string
  2328. */
  2329. function convertMACDec2Hex($decMAC, $inSeparator = '.', $outSeparator = ':', $reversed = false) {
  2330. $hexMAC = '';
  2331. if (!empty($decMAC)) {
  2332. $decMACArr = explode($inSeparator, $decMAC);
  2333. $decMACArr = ($reversed) ? array_reverse($decMACArr) : $decMACArr;
  2334. foreach ($decMACArr as $decOctet) {
  2335. $hexOctet = ($decOctet == '0' or $decOctet == 0) ? '00' : dechex($decOctet);
  2336. if (strlen($hexOctet) < 2) {
  2337. $hexOctet = '0' . $hexOctet;
  2338. }
  2339. $hexMAC .= $hexOctet;
  2340. }
  2341. $hexMAC = strtolower_utf8(AddMacSeparator($hexMAC, $outSeparator));
  2342. }
  2343. return ($hexMAC);
  2344. }
  2345. /**
  2346. * Makes "our standard truncate" of the raw SNMPWalk output,
  2347. * removing OID portion, OID value, leading and trailing dots and spaces
  2348. * TIP: if you need to trim some $snmpData without OID portion already
  2349. * - just set $oid parameter to an empty string
  2350. *
  2351. * @param string $snmpData
  2352. * @param string $oid
  2353. * @param string $removeValue
  2354. * @param bool $rowsExplode
  2355. * @param false $returnAsStr
  2356. *
  2357. * @param array|string $oidValue
  2358. *
  2359. * @return array|string
  2360. */
  2361. function trimSNMPOutput(
  2362. $snmpData,
  2363. $oid,
  2364. $removeValue = '',
  2365. $rowsExplode = false,
  2366. $returnAsStr = false,
  2367. $oidValue = array(
  2368. 'Counter32:',
  2369. 'Counter64:',
  2370. 'Gauge32:',
  2371. 'Gauge64:',
  2372. 'INTEGER:',
  2373. 'Hex-STRING:',
  2374. 'OID:',
  2375. 'Timeticks:',
  2376. 'STRING:',
  2377. 'Network Address:'
  2378. )
  2379. ) {
  2380. $result = ($returnAsStr) ? '' : array('', '');
  2381. if (!empty($snmpData)) {
  2382. if (!is_array($oidValue)) {
  2383. $oidValue = explode(',', $oidValue);
  2384. }
  2385. // removing OID portion
  2386. $snmpData = str_replace($oid, '', $snmpData);
  2387. // removing VALUE portion
  2388. $snmpData = str_replace($oidValue, '', $snmpData);
  2389. // removing some "specific" $removeValue
  2390. $snmpData = str_replace($removeValue, '', $snmpData);
  2391. if (!$returnAsStr) {
  2392. if ($rowsExplode) {
  2393. $snmpData = explodeRows($snmpData);
  2394. } else {
  2395. // trimming leading and trailing dots and spaces
  2396. $snmpData = trim($snmpData, '. \n\r\t');
  2397. $snmpData = explode('=', $snmpData);
  2398. if (isset($snmpData[1])) {
  2399. // trimming possible extra spaces
  2400. $snmpData[0] = trim($snmpData[0]);
  2401. $snmpData[1] = trim($snmpData[1]);
  2402. }
  2403. }
  2404. }
  2405. $result = $snmpData;
  2406. }
  2407. return ($result);
  2408. }
  2409. /**
  2410. * Returns array with range start and end IP from IP address with CIDR notation
  2411. *
  2412. * @param string $ipcidr
  2413. * @param bool $excludeNetworkAddr
  2414. * @param bool $excludeBroadcastAddr
  2415. *
  2416. * @return array startip/endip
  2417. */
  2418. function ipcidrToStartEndIP($ipcidr, $excludeNetworkAddr = false, $excludeBroadcastAddr = false) {
  2419. $range = array();
  2420. $ipcidr = explode('/', $ipcidr);
  2421. $startip = (ip2long($ipcidr[0])) & ((-1 << (32 - (int) $ipcidr[1])));
  2422. $endip = $startip + pow(2, (32 - (int) $ipcidr[1])) - 1;
  2423. $startip = ($excludeNetworkAddr ? $startip + 1 : $startip);
  2424. $endip = ($excludeBroadcastAddr ? $endip - 1 : $endip);
  2425. $range['startip'] = long2ip($startip);
  2426. $range['endip'] = long2ip($endip);
  2427. return ($range);
  2428. }
  2429. /**
  2430. * Just returns random-generated MAC
  2431. *
  2432. * @return string
  2433. */
  2434. function zb_MacGetRandom() {
  2435. $result = '14:' . '88' . ':' . rand(10, 99) . ':' . rand(10, 99) . ':' . rand(10, 99) . ':' . rand(10, 99);
  2436. return ($result);
  2437. }
  2438. /**
  2439. * Checks have some IP valid format or not?
  2440. *
  2441. * @param string $ip
  2442. *
  2443. * @return bool
  2444. */
  2445. function zb_isIPValid($ip) {
  2446. $result = false;
  2447. if (filter_var($ip, FILTER_VALIDATE_IP)) {
  2448. $result = true;
  2449. }
  2450. return ($result);
  2451. }