dashboard.php 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631
  1. <?php
  2. namespace MGModule\DNSManager2\controllers\addon\clientarea;
  3. use Exception;
  4. use MGModule\DNSManager2 as main;
  5. use MGModule\DNSManager2\helpers\custom\ClientFilesManage;
  6. use MGModule\DNSManager2\mgLibs\custom;
  7. use MGModule\DNSManager2\mgLibs\custom\AjaxResponse;
  8. use MGModule\DNSManager2\mgLibs\custom\dns\record\Record;
  9. use MGModule\DNSManager2\mgLibs\custom\dns\utils\IP;
  10. use MGModule\DNSManager2\mgLibs\custom\dns\utils\ReverseDNSHelper;
  11. use MGModule\DNSManager2\mgLibs\custom\helpers\RecordSetHelper;
  12. use MGModule\DNSManager2\mgLibs\custom\helpers\ZoneLogger\Manager as ZoneLoggerManager;
  13. use MGModule\DNSManager2\mgLibs\custom\manager\BlockerHelper;
  14. use MGModule\DNSManager2\mgLibs\custom\manager\ClientHelper;
  15. use MGModule\DNSManager2\mgLibs\custom\manager\GlobalSettingHelper;
  16. use MGModule\DNSManager2\mgLibs\custom\manager\LogHelper;
  17. use MGModule\DNSManager2\mgLibs\custom\manager\ZoneCreator;
  18. use MGModule\DNSManager2\mgLibs\custom\manager\ZoneRemover;
  19. use MGModule\DNSManager2\mgLibs\custom\relateditem\RelatedItem;
  20. use MGModule\DNSManager2\mgLibs\custom\reverse\IPHelper;
  21. use MGModule\DNSManager2\mgLibs\lang;
  22. use MGModule\DNSManager2\mgLibs\MySQL\query;
  23. use MGModule\DNSManager2\models\custom\globalsetting\GlobalSettingEnum;
  24. use MGModule\DNSManager2\models\custom\package\setting\PackageSettingEnum;
  25. use MGModule\DNSManager2\models\custom\reverse;
  26. use MGModule\DNSManager2\models\custom\server\setting\ServerSettingEnum;
  27. use MGModule\DNSManager2\models\custom\set;
  28. use MGModule\DNSManager2\models\custom\status;
  29. use MGModule\DNSManager2\models\custom\task;
  30. use MGModule\DNSManager2\models\custom\zone\Zone;
  31. use WHMCS\Database\Capsule as DB;
  32. //TODO: (nie miałem gdzie dodać) Synchronizacja rdnsów (w obie strony, porównywac rekordy z serverem)
  33. //TODO: edit zone -> records encode itp
  34. //TODO: ogarnąć ten bajzel w kontrolerach
  35. class dashboard extends main\mgLibs\process\abstractController
  36. {
  37. private $set_form = array(
  38. 'edit' => false,
  39. 'name' => '',
  40. 'count' => 0,
  41. );
  42. public function __construct($input)
  43. {
  44. parent::__construct($input);
  45. if($_REQUEST['mg-action'] == 'manageRDNS' && GlobalSettingHelper::getSetting(GlobalSettingEnum::RDNS_IN_CLIENTAREA) == GlobalSettingEnum::CLIENTAREA_RNDS_BLOCK)
  46. {
  47. redir('m=DNSManager2');
  48. }
  49. }
  50. function indexHTML($input, $vars = array())
  51. {
  52. $this->redirectIfIsOnlyRDNSforCA();
  53. $helper = new ClientHelper($_SESSION['uid']);
  54. $groups = $helper->getGroups();
  55. $groups_info = array();
  56. foreach($groups as $key => $group)
  57. {
  58. $sum = array();
  59. $zones_count = 0;
  60. foreach($group as $key2 => $zone)
  61. {
  62. if($zone['zone_id'])
  63. {
  64. $check = $helper::getServerStatusByZoneId($zone['zone_id']);
  65. $group[$key2]['server_status'] = $check['status'];
  66. $zones_count++;
  67. }
  68. $sum[$zone['type'] .'::'.$zone['relid']] = $zone['zones_available'];
  69. }
  70. $groups_info[$key]['zones_available'] = array_sum($sum);
  71. $groups_info[$key]['zones_count'] = $zones_count;
  72. $groups_info[$key]['type'] = $zone['type'];
  73. $groups_info[$key]['relid'] = $zone['relid'];
  74. $groups_info[$key]['full'] = $groups_info[$key]['zones_available'] <= $groups_info[$key]['zones_count'];
  75. $obGroup = new \stdClass();
  76. $obGroup->group = $group;
  77. $obGroup->product_group_name = $zone['product_group_name'];
  78. $obGroup->product_name = $zone['product_name'];
  79. $obGroup->product_id = $zone['product_id'];
  80. $obGroup->domain = $zone['domain'];
  81. $obGroup->groupKey = $key;
  82. $groups[$key] = $obGroup;
  83. }
  84. unset($key);
  85. usort($groups, $this->arraySortByValue('domain'));
  86. if($groups[0]->groupKey === 'Other')
  87. {
  88. $groups[] = $groups[0];
  89. unset($groups[0]);
  90. }
  91. $vars['groups'] = $groups;
  92. $vars['groups_info'] = $groups_info;
  93. $vars['manage_rdns'] = $this->getRDNSStatus();
  94. $vars['manageRecordsSets'] = GlobalSettingHelper::getSetting(GlobalSettingEnum::LINK_TO_DNS_SETS_MANAGER, true);
  95. $vars['clientarea_import_export'] = GlobalSettingHelper::getSetting(GlobalSettingEnum::LINK_TO_CLIENTAREA_IMPORT_EXPORT, true);
  96. $vars['showProductName'] = GlobalSettingHelper::getSetting(GlobalSettingEnum::SHOW_PRODUCT_NAME, false);
  97. return [
  98. 'tpl' => 'dashboard',
  99. 'vars' => $vars
  100. ];
  101. }
  102. /**
  103. * @return bool
  104. */
  105. private function getRDNSStatus()
  106. {
  107. if( GlobalSettingHelper::getSetting(GlobalSettingEnum::RDNS_IN_CLIENTAREA, true) !== 'clientarea_rdns_allow' )
  108. {
  109. return false;
  110. }
  111. $rdnsPossibleToAdd = (bool)count($this->getUserPackageItems($_SESSION['uid']));
  112. $rdnsAlreadyCreated = (bool)query::query("SELECT COUNT(`id`)
  113. FROM `dns_manager2_reverse`
  114. WHERE `clientid` = :clientid", ['clientid' => $_SESSION['uid']])->fetchColumn();
  115. if(!$rdnsAlreadyCreated && !$rdnsPossibleToAdd)
  116. {
  117. return false;
  118. }
  119. return true;
  120. }
  121. public function addZoneJSON($input, $vars = array())
  122. {
  123. //TODO: sytuacje gdy ip nie jest konieczne w module + default ip
  124. $vars = IPHelper::getIPsArray($_SESSION['uid'], $input['type'], $input['relid']);
  125. $vars['ipmanager'] = !empty($vars['pools']);
  126. $vars['type'] = $input['type'];
  127. $vars['relid'] = $input['relid'];
  128. $vars['custom_ip'] = IPHelper::isCustomIPEnabledForZoneCreate();
  129. $helper = new ClientHelper($_SESSION['uid']);
  130. $allowed_ips = $helper->getPackageAllowedIps(intval($vars['relid']), intval($vars['type']));
  131. $vars['allowed_ips'] = IP::getAvailableIpList(json_decode($allowed_ips['allowed_ips']));
  132. $vars['allowed_ips_flag'] = is_array($vars['allowed_ips']) && !empty($vars['allowed_ips']) && $vars['allowed_ips'][0] != null;
  133. $ip_blacklist = $helper->getPackageIpBlacklist(intval($vars['relid']), intval($vars['type']));
  134. $vars['ip_blacklist'] = IP::getAvailableIpList(json_decode($ip_blacklist['ip_blacklist']));
  135. $vars['ip_blacklist_flag'] = is_array($vars['ip_blacklist']) && !empty($vars['ip_blacklist']) && $vars['allowed_ips'][0] != null;
  136. if($input['type'] != main\models\custom\zone\ZoneTypeEnum::DOMAIN)
  137. {
  138. $vars['is_not_domain'] = true;
  139. }
  140. if($input['type'] == '0' && $input['relid'] == '0')
  141. {
  142. $vars['custom_ip'] = 1;
  143. $creator = new ZoneCreator('', $input['type'], $input['relid'], false, $_SESSION['uid']);
  144. }
  145. else
  146. {
  147. $creator = new ZoneCreator('', $input['type'], $input['relid']);
  148. }
  149. $vars['is_ip_required'] = true;
  150. if ($creator->server) {
  151. $vars['is_ip_required'] = $creator->server->getModule()->isIPRequired();
  152. }
  153. $defaultSets = $creator->getPackage()->getAdminSets();
  154. $adminSets = set\Repository::factory()->adminOnly()->get();
  155. foreach ($adminSets as $key => $value) {
  156. if( !in_array( $value->id, $defaultSets))
  157. {
  158. unset($adminSets[$key]);
  159. }
  160. }
  161. $vars['zoneDomainItems'] = custom\helpers\ZoneSettings::getProperlyItems($_SESSION['uid'], $vars['relid'], $vars['type']);
  162. $vars['adminSets'] = $adminSets;
  163. $vars['allowManageRecordsSets'] = GlobalSettingHelper::getSetting(GlobalSettingEnum::LINK_TO_DNS_SETS_MANAGER, true);
  164. $vars['recordSets'] = set\Repository::factory()->byUserId((int)$_SESSION['uid'])->get();
  165. $vars['allowManageRecordsSets'] = (count($vars['recordSets']) > 0 || count($vars['adminSets']) > 0) ? $vars['allowManageRecordsSets'] : false;
  166. return AjaxResponse::I()->modal('add-zone', $vars)->toArray();
  167. }
  168. public function addZoneSaveJSON($input, $vars = array())
  169. {
  170. $helper = new ClientHelper($_SESSION['uid']);
  171. if(!$helper->canUserCreatesNewZonesIn($input['type'], $input['relid'])) {
  172. return AjaxResponse::I()->addError('you_cant_add_new_zones_within_this_group')->toArray();
  173. }
  174. if(GlobalSettingHelper::getSetting(GlobalSettingEnum::OWNED_DOMAINS_ONLY) == 'on' && !in_array($input['zone_name'], $helper->getClientDomains())) {
  175. return AjaxResponse::I()->addError('you_cant_use_domain_that_does_not_belong_to_you')->toArray();
  176. }
  177. $zoneName = $input['zone_name'];
  178. $blockerHelper = new BlockerHelper();
  179. $isBlocked = false;
  180. $allowedIps = json_decode($helper->getPackageAllowedIps($input['relid'],$input['type'])['allowed_ips']);
  181. $ipBlacklist = json_decode($helper->getPackageIpBlacklist($input['relid'],$input['type'])['ip_blacklist']);
  182. if($input['is_ip_required']) {
  183. if (is_array($allowedIps) && !empty($allowedIps)) {
  184. if (!in_array($input['zone_ip'], $allowedIps)) return AjaxResponse::I()->addError('not_allowed_ip')->toArray();
  185. }
  186. if (in_array($input['zone_ip'], $ipBlacklist))
  187. return AjaxResponse::I()->addError('ip_on_blacklist')->toArray();
  188. }
  189. if(!$blockerHelper->isLoggedUserExcluded()) {
  190. $rules = $blockerHelper->getRules();
  191. foreach($rules as $rule) {
  192. $rule = trim($rule);
  193. if($blockerHelper->isRecordBlocked($rule, $zoneName)) {
  194. $isBlocked = true;
  195. break;
  196. }
  197. }
  198. }
  199. if($isBlocked) {
  200. return AjaxResponse::I()->addError('value_is_blocked')->toArray();
  201. }
  202. if(strpos($input['zone_ip'], 'block') !== false) {
  203. list($str,$pool,$mask) = explode('|',$input['zone_ip']);
  204. $ip = new IP($input['zone_ip_from_block']);
  205. if(!$ip->isInNetwork($pool, $mask)) {
  206. return AjaxResponse::I()->addError('ip_is_not_belongs_to_selected_block')->toArray();
  207. }
  208. $input['zone_ip'] = $input['zone_ip_from_block'];
  209. }
  210. // $ip_array = IPHelper::getIPsArray($_SESSION['uid'], $input['type'], $input['relid']);
  211. // if(!in_array($input['zone_ip'], $ip_array['all_ips']) && !empty($input['zone_ip'])) {
  212. // return AjaxResponse::I()->addError('you_cant_use_ip_that_not_belongs_to_you')->toArray();
  213. // }
  214. if(!custom\helpers\ZoneSettings::isDomainClient($input['zone_name'], $input['type'], $input['relid'], $_SESSION['uid']))
  215. {
  216. return AjaxResponse::I()->addError('zone_does_not_belongToYou')->toArray();
  217. }
  218. try
  219. {
  220. $ip = new IP($input['zone_ip']);
  221. if(!empty($input['zone_ip']) && (!$ip->isValid() || $input['type'] != '0' || $input['relid'] != '0'))
  222. {
  223. IPHelper::validateIfClientCanUseIP($_SESSION['uid'], $input['type'], $input['relid'], $input['zone_ip'], true);
  224. }
  225. $creator = new ZoneCreator($input['zone_name'], $input['type'], $input['relid'], $input['zone_ip'], $_SESSION['uid']);
  226. $creator->setZoneLoggerManager(new ZoneLoggerManager($_SESSION['uid']));
  227. $packageID = $creator->getPackage()->id;
  228. $limitCheck = main\mgLibs\custom\helpers\RecordSetHelper::checkAllowedRecordsLimits($packageID, $input['recordSet']);
  229. if(!$limitCheck)
  230. {
  231. return AjaxResponse::I()->addError('you_have_exceeded_limit')->toArray();
  232. }
  233. $ret = $creator->create($input['recordSet']);
  234. if(is_string($ret))
  235. {
  236. return AjaxResponse::I()->addRawError($ret)->toArray();
  237. }
  238. AjaxResponse::I()->addInfo('zone_created_successfully');
  239. }
  240. catch(Exception $exc)
  241. {
  242. AjaxResponse::I()->addRawError($exc->getMessage());
  243. }
  244. return AjaxResponse::I()->refreshPage($this->indexHTML($input))->toArray();
  245. }
  246. public function removeZoneJSON($input, $vars = array()) {
  247. $helper = new ClientHelper($_SESSION['uid']);
  248. $zone = new Zone($input['zone_id']);
  249. if(!$helper->isZoneOwnedByClient($zone)) {
  250. return AjaxResponse::I()->addError('you_cant_remove_this_zone_because_it_is_not_belongs_to_you')->toArray();
  251. }
  252. if($zone->is_locked){
  253. return AjaxResponse::I()->addError('you_cannot_edit_zone_that_is_not_your_own_zone')->toArray();
  254. }
  255. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  256. if(!$checkServer['status'])
  257. {
  258. return AjaxResponse::I()->addError('you_cannot_remove_this_zone_because_server_is_not_active')->toArray();
  259. }
  260. try {
  261. ZoneRemover::removeZone($zone);
  262. main\mgLibs\custom\helpers\StatusHelper::removeZoneStatus($input['id']);
  263. $zoneLoggerManager = new ZoneLoggerManager($_SESSION['uid']);
  264. $zoneLoggerManager->logTerminateZoneAction($zone);
  265. // LogHelper::addSuccessLogUsingZone('Remove Zone', '', $zone);
  266. } catch (Exception $exc) {
  267. LogHelper::addFailLogUsingZone('Remove Zone', $exc->getMessage(), $zone);
  268. throw $exc;
  269. }
  270. AjaxResponse::I()->refreshPage($this->indexHTML($input));
  271. AjaxResponse::I()->addInfo('zone_removed_successfully');
  272. return AjaxResponse::I()->toArray();
  273. }
  274. public function createZoneJSON($input, $vars = array())
  275. {
  276. $helper = new ClientHelper($_SESSION['uid']);
  277. $zone = new Zone($input['zone_id']);
  278. if(!$helper->isZoneOwnedByClient($zone))
  279. {
  280. return AjaxResponse::I()->addError('you_cant_create_this_zone_because_it_is_not_belongs_to_you')->toArray();
  281. }
  282. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  283. if(!$checkServer['status'])
  284. {
  285. return AjaxResponse::I()->addError('you_cannot_create_this_zone_because_server_is_not_active')->toArray();
  286. }
  287. try
  288. {
  289. $zoneLogger = new main\mgLibs\custom\helpers\ZoneLogger\Manager($_SESSION['uid']);
  290. $module = $zone->getModule();
  291. if(!$module->zoneExists())
  292. {
  293. $module->activateZone();
  294. $zoneLogger->logCreateZoneAction($zone);
  295. }
  296. $setHelper = new main\mgLibs\custom\helpers\RecordSetHelper($zone, $zoneLogger);
  297. $setHelper->addRecordSet();
  298. $zone->setThatExist();
  299. // LogHelper::addSuccessLogUsingZone('Add Zone', '', $zone);
  300. }
  301. catch(Exception $exc)
  302. {
  303. LogHelper::addFailLogUsingZone('Add Zone', $exc->getMessage(), $zone);
  304. throw $exc;
  305. }
  306. AjaxResponse::I()->refreshPage($this->indexHTML($input));
  307. AjaxResponse::I()->addInfo('zone_created_successfully');
  308. return AjaxResponse::I()->toArray();
  309. }
  310. private function checkWhmcsProductStatus($type, $relid)
  311. {
  312. switch($type)
  313. {
  314. case 1:
  315. $status = main\mgLibs\MySQL\query::select(array('status'), 'tbldomains', array('id' => $relid))->fetchAll();
  316. $status = $status[0]['status'];
  317. break;
  318. case 2:
  319. $status = main\mgLibs\MySQL\query::select(array('domainstatus'), 'tblhosting', array('id' => $relid))->fetchAll();
  320. $status = $status[0]['domainstatus'];
  321. break;
  322. case 3:
  323. $status = main\mgLibs\MySQL\query::select(array('status'), 'tblhostingaddons', array('id' => $relid))->fetchAll();
  324. $status = $status[0]['status'];
  325. break;
  326. default:
  327. $status = 'Active';
  328. break;
  329. }
  330. return strtolower($status);
  331. }
  332. public function editZoneHTML($input, $vars = array())
  333. {
  334. $this->redirectIfIsOnlyRDNSforCA();
  335. $helper = new ClientHelper($_SESSION['uid']);
  336. $zone = new Zone($input['zone_id']);
  337. $whmcsOrderStatus = $this->checkWhmcsProductStatus($zone->type, $zone->relid) == 'active' ? false : true;
  338. if($this->isTransferAndShouldBeAbleToEdit($zone))
  339. {
  340. $whmcsOrderStatus = false;
  341. }
  342. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  343. if(!$helper->isZoneOwnedByClient($zone))
  344. {
  345. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_it_is_not_belongs_to_you');
  346. }
  347. elseif(!$checkServer['status'])
  348. {
  349. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_server_is_not_active');
  350. }elseif ($zone->is_locked){
  351. $vars['error'] = lang::T('You cannot edit this zone because it\'s locked');
  352. }elseif ($whmcsOrderStatus)
  353. {
  354. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_order_is_not_active');
  355. }
  356. else
  357. {
  358. $module = $zone->getModule();
  359. if(!$module->zoneExists())
  360. {
  361. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_it_is_terminated_on_server');
  362. $zone->setThatNotExist();
  363. }
  364. else
  365. {
  366. $vars['zone_name'] = $zone->name;
  367. $vars['zoneid'] = $zone->id;
  368. $vars['ttl_disabled'] = !$module->isTTLEnabled();
  369. $vars['records'] = $module->getRecords();
  370. $vars['records'] = array_merge($vars['records'], $this->getPTRRecords($zone));
  371. $soaList = array();
  372. $limits = $this->getPackageRecordsLimits($zone);
  373. foreach($vars['records'] as $key => &$record)
  374. {
  375. if(!isset($limits[$record->type]) ){
  376. unset($vars['records'][$key]);
  377. }
  378. $record->encode();
  379. if($record->type === 'SOA' && array_key_exists('SOA', $limits))
  380. {
  381. $soaList[] = $record;
  382. unset($vars['records'][$key]);
  383. }
  384. }
  385. usort($vars['records'], $this->arraySortByValue('type'));
  386. foreach($soaList as $soaRecord)
  387. {
  388. array_unshift($vars['records'] , $soaRecord);
  389. }
  390. $rep = status\Repository::factory()->setFilter('relid', $zone->id)->get();
  391. if(!$rep)
  392. {
  393. $status = 'pending';
  394. }
  395. else
  396. {
  397. $status = $rep[0]->status;
  398. }
  399. $status = main\mgLibs\custom\helpers\StatusHelper::parseStatus($status);
  400. $soaAlert = GlobalSettingHelper::getSetting(GlobalSettingEnum::SOA_IS_NOT_NS_STATUS);
  401. $domainAvailableAlert = GlobalSettingHelper::getSetting(GlobalSettingEnum::WHOIS_MISSING_STATUS);
  402. $activeAlert = GlobalSettingHelper::getSetting(GlobalSettingEnum::IS_OK_STATUS);
  403. $pendingAlert = GlobalSettingHelper::getSetting(GlobalSettingEnum::IS_PENDING_STATUS);
  404. if($status == 'pending' && $pendingAlert == 'on')
  405. {
  406. $vars['tpl'] = 'pending';
  407. }
  408. elseif($status == 'notRegistered' && $domainAvailableAlert == 'on')
  409. {
  410. $vars['tpl'] = 'notRegistered';
  411. }
  412. elseif($status == 'soaWarning' && $soaAlert == 'on')
  413. {
  414. $vars['tpl'] = 'soaWarning';
  415. }
  416. elseif($status == 'active' && $activeAlert == 'on')
  417. {
  418. $vars['tpl'] = 'active';
  419. }
  420. else
  421. {
  422. $vars['tpl'] = 'standard';
  423. }
  424. $content = main\mgLibs\custom\helpers\StatusHelper::loadStatusContent($vars['tpl']);
  425. $recordLimits = $this->getPackageRecordsLimits($zone);
  426. array_walk($recordLimits, function (&$limit) use ($recordLimits){
  427. if ((int)$limit === -1 && isset($recordLimits['total']))
  428. {
  429. $limit = $recordLimits['total'];
  430. }
  431. });
  432. $vars['available_record_types'] = $module->getAvailableRecordTypes();
  433. $vars['content'] = html_entity_decode(str_replace('{$domain}', $zone->name, $content));
  434. $vars['counter'] = 0;
  435. $vars['zone_name'] = $zone->name;
  436. $vars['id'] = $zone->id;
  437. $vars['records_count'] = $this->countRecords($vars['records']);
  438. $vars['limits'] = $recordLimits;
  439. $vars['enable_dnssec'] = $zone->getServer()->getSettings(ServerSettingEnum::ENABLE_DNSSEC) == 'on' && $module->isDNSSECSupported();
  440. $showNameservers = GlobalSettingHelper::getSetting(GlobalSettingEnum::SHOW_NAMESERVERS);
  441. $vars['nameservers'] = $showNameservers == 'on' ? $module->getNameServers(false) : [];
  442. }
  443. }
  444. $vars['show_full_record_name'] = GlobalSettingHelper::getSetting(GlobalSettingEnum::SHOW_FULL_RECORD_NAME);
  445. return array(
  446. 'tpl' => 'edit',
  447. 'vars' => $vars
  448. );
  449. }
  450. private function getPTRRecords($zone) {
  451. $out = array();
  452. foreach(reverse\Repository::factory()->from($zone->getServer()->id, $zone->name)->byClientID($zone->clientid)->get() as $data) {
  453. $ptr = new main\mgLibs\custom\dns\record\Record();
  454. $ptr->name = ReverseDNSHelper::reverseRecordName($data->ip) . '.' . $data->name;
  455. $ptr->type = 'PTR';
  456. $ptr->ttl = $data->ttl;
  457. $ptr->ip = $data->ip;
  458. $ptr->createRDATAObject('PTR');
  459. $ptr->rdata->setFirstProperty(empty($data->sub)?$data->from:$data->sub . '.' . $data->from);
  460. $out[] = $ptr;
  461. }
  462. return $out;
  463. }
  464. private function getPackageRecordsLimits(Zone $zone) {
  465. $package = $zone->getPackage();
  466. if($package == false) {
  467. return array('total' => 0);
  468. }
  469. $out = unserialize($package->getSettings(PackageSettingEnum::ALLOWED_RECORD_TYPES))?:array();
  470. $out['total'] = $this->getTotalRecordsLimit($zone);
  471. if(isset($out['PTR'])) {
  472. if($zone->getServer()->getSettings(ServerSettingEnum::ALLOW_RDNS) == 'on') {
  473. if($out['PTR'] > 1 && !($zone->getServer()->getSettings(ServerSettingEnum::ALLOW_MULTIPLE_PTR) == 'on')) {
  474. $out['PTR'] = 1;
  475. }
  476. } else {
  477. unset($out['PTR']);
  478. }
  479. }
  480. return $out;
  481. }
  482. private function countRecords($records) {
  483. $records_count = array();
  484. foreach($records as $record) {
  485. $records_count[$record->type]++;
  486. }
  487. $records_count['total'] = array_sum($records_count);
  488. return $records_count;
  489. }
  490. private function getTotalRecordsLimit(Zone $zone) {
  491. return $zone->getPackageItem()->limit;
  492. }
  493. public function editZoneJSON($input, $vars = array()) {
  494. return AjaxResponse::I()->refreshPage($this->editZoneHTML($input))->toArray();
  495. }
  496. public function removeRecordJSON($input, $vars = array()) {
  497. $helper = new ClientHelper($_SESSION['uid']);
  498. $zone = new Zone($input['zone_id']);
  499. if(!$helper->isZoneOwnedByClient($zone)) {
  500. return AjaxResponse::I()->addError('you_cant_remove_this_record_because_it_is_not_belongs_to_one_of_your_zones')->toArray();
  501. }
  502. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  503. if(!$checkServer['status'])
  504. {
  505. return AjaxResponse::I()->addError('you_cannot_edit_this_zone_because_server_is_not_active')->toArray();
  506. }
  507. try {
  508. $record_data = array_pop($input['record']);
  509. if(empty($record_data))
  510. {
  511. $record_data = array_pop($input['edit_record']);
  512. }
  513. $module = $zone->getModule();
  514. if (strtoupper($record_data['type']) == 'PTR') { // REVERSE RECORD
  515. $ip = $record_data['ip'];
  516. $record = reverse\Repository::factory()->fromIP($zone->getServer()->id, $ip)->one();
  517. if ($record === FALSE || $record->from != $zone->name) {
  518. return AjaxResponse::I()->addError('you_cannot_remove_record_that_is_not_belongs_to_you')->toArray();
  519. }
  520. $module->removeRDNS($ip);
  521. $record->delete();
  522. } else {
  523. $record = $this->createRecordFromInputData($record_data);
  524. $module->deleteRecord($record);
  525. }
  526. $zoneLoggerManager = new ZoneLoggerManager($_SESSION['uid']);
  527. $zoneLoggerManager->logRemoveRecordFromZone($zone, $record);
  528. } catch (Exception $exc) {
  529. LogHelper::addFailLogUsingZone('Edit Zone', $exc->getMessage(), $zone);
  530. throw $exc;
  531. }
  532. AjaxResponse::I()->addInfo('record_removed_successfully');
  533. AjaxResponse::I()->refreshPage($this->editZoneHTML($input));
  534. return AjaxResponse::I()->toArray();
  535. }
  536. private function createRecordFromInputData($input) {
  537. $record = Record::tryToCreateFromArray($input);
  538. $record->rdata->setDataFromArray($input['field']);
  539. $record->decode();
  540. return $record;
  541. }
  542. public function addRecordJSON($input, $vars = array()) {
  543. $helper = new ClientHelper($_SESSION['uid']);
  544. $zone = new Zone($input['zone_id']);
  545. $vars = IPHelper::getIPsArray($_SESSION['uid'], $zone->type, $zone->relid);
  546. $vars['ipmanager'] = !empty($vars['pools']);
  547. $vars['zone_id'] = $zone->id;
  548. $vars['available_record_types'] = $zone->getModule()->getAvailableRecordTypes();
  549. $vars['custom_ip'] = IPHelper::isCustomIPEnabled();
  550. $vars['ttl_enabled'] = $zone->getModule()->isTTLEnabled();
  551. $helper = new ClientHelper($_SESSION['uid']);
  552. if($vars['recordsAllowedIp']) {
  553. $allowedIps = $helper->getPackageAllowedIps(intval($zone->relid), intval($zone->type));
  554. $allowedIps = IP::getAvailableIpList(json_decode($allowedIps['allowed_ips']));
  555. $vars['allowed_ipv4'] = IP::getOnlyIpv4($allowedIps);
  556. $vars['allowed_ipv4_flag'] = is_array($vars['allowed_ipv4']) && !empty($vars['allowed_ipv4']) && $vars['allowed_ipv4'][0] != null;
  557. $vars['allowed_ipv6'] = IP::getOnlyIpv6($allowedIps);
  558. $vars['allowed_ipv6_flag'] = is_array($vars['allowed_ipv6']) && !empty($vars['allowed_ipv6']) && $vars['allowed_ipv6'][0] != null;
  559. }
  560. if($vars['recordsBlacklist']) {
  561. $ipBlacklist = $helper->getPackageIpBlacklist(intval($zone->relid), intval($zone->type));
  562. $ipBlacklist = IP::getAvailableIpList(json_decode($ipBlacklist['ip_blacklist']));
  563. $vars['ipv4_blacklist'] = IP::getOnlyIpv4($ipBlacklist);
  564. $vars['ipv4_blacklist_flag'] = is_array($vars['ipv4_blacklist']) && !empty($vars['ipv4_blacklist']) && $vars['ipv4_blacklist'][0] != null;
  565. $vars['ipv6_blacklist'] = IP::getOnlyIpv6($ipBlacklist);
  566. $vars['ipv6_blacklist_flag'] = is_array($vars['ipv6_blacklist']) && !empty($vars['ipv6_blacklist']) && $vars['ipv6_blacklist'][0] != null;
  567. }
  568. $limits = $this->getPackageRecordsLimits($zone);
  569. foreach($vars['available_record_types'] as $k => $record) {
  570. if(!isset($limits[$record]) || $input['records'][$record] >= $limits[$record] && (int)$limits[$record] !== -1)
  571. unset($vars['available_record_types'][$k]);
  572. }
  573. return AjaxResponse::I()->modal('add-record', $vars)->toArray();
  574. }
  575. public function addRecordSaveJSON($input, $vars = array()) {
  576. if(empty($input['type'])) {
  577. return AjaxResponse::I()->addError('choose_record_type')->toArray();
  578. }
  579. $helper = new ClientHelper($_SESSION['uid']);
  580. $zone = new Zone($input['zone_id']);
  581. if(!$helper->isZoneOwnedByClient($zone)) {
  582. return AjaxResponse::I()->addError('you_cannot_add_record_to_zone_that_is_not_yours')->toArray();
  583. }
  584. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  585. if(!$checkServer['status'])
  586. {
  587. return AjaxResponse::I()->addError('you_cannot_edit_this_zone_because_server_is_not_active')->toArray();
  588. }
  589. $ipBlacklist = IP::getAvailableIpList(json_decode($helper->getPackageIpBlacklist(intval($zone->relid), intval($zone->type))['ip_blacklist']));
  590. if($input['type'] === 'PTR')
  591. $ip = $input['ip'];
  592. else
  593. $ip = $input['field']['address'];
  594. if($ip && !empty($ipBlacklist) && in_array($ip, $ipBlacklist) && $ipBlacklist[0] != null)
  595. return AjaxResponse::I()->addError('ip_on_blacklist')->toArray();
  596. $blockerHelper = new BlockerHelper();
  597. $isBlocked = false;
  598. if(!$blockerHelper->isLoggedUserExcluded()) {
  599. $rules = $blockerHelper->getRules();
  600. foreach($rules as $rule) {
  601. $rule = trim($rule);
  602. if($blockerHelper->isRecordBlocked($rule, $input['name'])) {
  603. $isBlocked = true;
  604. break;
  605. }
  606. }
  607. }
  608. if($isBlocked) {
  609. return AjaxResponse::I()->addError('value_is_blocked')->toArray();
  610. }
  611. $module = $zone->getModule();
  612. try {
  613. $limits = $this->getPackageRecordsLimits($zone);
  614. $count = $this->countRecords($module->getRecords());
  615. if((isset($limits[$input['type']])
  616. && (int)$limits[$input['type']] !== -1
  617. && $count[$input['type']] >= $limits[$input['type']])
  618. || $limits['total'] <= $count['total'] ) {
  619. return AjaxResponse::I()->addError('you_cant_add_this_record_because_you_reach_limit')->toArray();
  620. }
  621. if(strtoupper($input['type']) == 'PTR') {
  622. if(strpos($input['ip'], 'block') !== false) {
  623. list($str,$pool,$mask) = explode('|',$input['ip']);
  624. $ip = new IP($input['ip_from_block']);
  625. if(!$ip->isInNetwork($pool, $mask)) {
  626. return AjaxResponse::I()->addError('ip_is_not_belongs_to_selected_block')->toArray();
  627. }
  628. $input['ip'] = $input['ip_from_block'];
  629. }
  630. $ip = $input['ip'];
  631. // if(empty($ip)) {
  632. // return AjaxResponse::I()->addError('ip_cannot_be_empty')->toArray();
  633. // }
  634. //
  635. // $ip_array = IPHelper::getIPsArray($_SESSION['uid'], $zone->type, $zone->relid);
  636. // if(!in_array($ip, $ip_array['all_ips'])) {
  637. // return AjaxResponse::I()->addError('you_cant_use_ip_that_not_belongs_to_you')->toArray();
  638. // }
  639. IPHelper::validateIfClientCanUseIP($_SESSION['uid'], $zone->type, $zone->relid, $ip);
  640. $input['subdomain'] = trim($input['subdomain']);
  641. $name = !empty($input['subdomain'])?$input['subdomain'].'.'.$zone->name: $zone->name;
  642. $record = new main\mgLibs\custom\reverse\ReverseDNS($zone);
  643. $record->setDomain($name);
  644. $record->setIP($ip);
  645. $record->setTTL($input['ttl']);
  646. $record->create();
  647. } else {
  648. $record = $this->createRecordFromInputData($input);
  649. $record->encode();
  650. $module->validateRecord($record);
  651. $record->nameToAbsolute($zone->name);
  652. $module->addRecord($record);
  653. }
  654. $zoneLoggerManager = new ZoneLoggerManager($_SESSION['uid']);
  655. $zoneLoggerManager->logAddRecordToZone($zone, $record);
  656. // LogHelper::addSuccessLogUsingZone('Edit Zone', '', $zone);
  657. AjaxResponse::I()->addInfo('new_record_added_to_zone');
  658. return $this->editZoneJSON($input, $vars);
  659. }
  660. catch (custom\dns\exceptions\DNSSubmoduleHiddenException $exc )
  661. {
  662. LogHelper::addFailLogUsingZone('Edit Zone', $exc->getMessage(), $zone);
  663. return AjaxResponse::I()->addRawError('Problem while validating zone by bind. Please contact administrator')->toArray();
  664. }
  665. catch (Exception $exc) {
  666. LogHelper::addFailLogUsingZone('Edit Zone', $exc->getMessage(), $zone);
  667. return AjaxResponse::I()->addRawError($exc->getMessage())->toArray();
  668. }
  669. }
  670. private function createReverseIP(Zone $zone, $ip, $ttl, $sub = '') {
  671. $reverse = new reverse\Reverse();
  672. $reverse->serverid = $zone->getServer()->id;
  673. $reverse->from = $zone->name;
  674. $reverse->sub = $sub;
  675. $reverse->name = ReverseDNSHelper::reverseZoneName($ip);
  676. $reverse->created_at= date('Y-m-d H:i:s');
  677. $reverse->ip = $ip;
  678. $reverse->ttl = $ttl;
  679. $reverse->clientid = $zone->clientid;
  680. $reverse->save();
  681. }
  682. public function getRecordRdataJSON($input, $vars = array()) {
  683. $zone = new Zone($input['zone_id']);
  684. $class = '\MGModule\DNSManager2\mgLibs\custom\dns\record\type\\' . $input['type'];
  685. if(class_exists($class)) {
  686. $obj = new $class();
  687. $vars['record_fields'] = get_object_vars($obj);
  688. $vars['record_type'] = $input['type'];
  689. $packageSettings = $zone->getPackage()->getSettings('default_ttl');
  690. $packageSettings = unserialize($packageSettings);
  691. $vars['ttl_default_value'] = $packageSettings[$input['type']];
  692. if(empty($vars['ttl_default_value']))
  693. $vars['ttl_default_value'] = 14440;
  694. if($input['type'] == 'PTR') {
  695. $vars['value'] = $zone->name;
  696. }
  697. $settingRepo = new main\models\custom\package\setting\Repository();
  698. $vars['recordsAllowedIp'] = $settingRepo->byKey('records_allowed_ip')->get()[0] == 'on';
  699. $vars['recordsBlacklist'] = $settingRepo->byKey('records_blacklist')->get()[0] == 'on';
  700. $helper = new ClientHelper($_SESSION['uid']);
  701. if($vars['recordsAllowedIp']) {
  702. $allowedIps = $helper->getPackageAllowedIps(intval($zone->relid), intval($zone->type));
  703. $allowedIps = IP::getAvailableIpList(json_decode($allowedIps['allowed_ips']));
  704. $vars['allowed_ipv4'] = IP::getOnlyIpv4($allowedIps);
  705. $vars['allowed_ipv4_flag'] = is_array($vars['allowed_ipv4']) && !empty($vars['allowed_ipv4']) && $vars['allowed_ipv4'][0] != null;
  706. $vars['allowed_ipv6'] = IP::getOnlyIpv6($allowedIps);
  707. $vars['allowed_ipv6_flag'] = is_array($vars['allowed_ipv6']) && !empty($vars['allowed_ipv6']) && $vars['allowed_ipv6'][0] != null;
  708. }
  709. if($vars['recordsBlacklist']) {
  710. $ipBlacklist = $helper->getPackageIpBlacklist(intval($zone->relid), intval($zone->type));
  711. $ipBlacklist = IP::getAvailableIpList(json_decode($ipBlacklist['ip_blacklist']));
  712. $vars['ipv4_blacklist'] = IP::getOnlyIpv4($ipBlacklist);
  713. $vars['ipv4_blacklist_flag'] = is_array($vars['ipv4_blacklist']) && !empty($vars['ipv4_blacklist']) && $vars['ipv4_blacklist'][0] != null;
  714. $vars['ipv6_blacklist'] = IP::getOnlyIpv6($ipBlacklist);
  715. $vars['ipv6_blacklist_flag'] = is_array($vars['ipv6_blacklist']) && !empty($vars['ipv6_blacklist']) && $vars['ipv6_blacklist'][0] != null;
  716. }
  717. AjaxResponse::I()->html = main\mgLibs\smarty::I()->view('record-rdata',
  718. $vars,
  719. main\addon::getModuleTemplatesDir().DS.'pages' . DS . main\addon::I()->page);
  720. AjaxResponse::I()->ttl = $vars['ttl_default_value'];
  721. } else {
  722. AjaxResponse::I()->addRawError(main\mgLibs\lang::T('cannot_find_class'). ' ' .$class);
  723. }
  724. return AjaxResponse::I()->toArray();
  725. }
  726. public function editZoneSaveJSON($input, $vars = array())
  727. {
  728. $helper = new ClientHelper($_SESSION['uid']);
  729. $zone = new Zone($input['zone_id']);
  730. if(!$helper->isZoneOwnedByClient($zone))
  731. {
  732. return AjaxResponse::I()->addError('you_cannot_edit_zone_that_is_not_your_own_zone')->toArray();
  733. }
  734. if($zone->is_locked) return AjaxResponse::I()->addError('you_cannot_edit_zone_that_is_not_your_own_zone')->toArray();
  735. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  736. if(!$checkServer['status'])
  737. {
  738. return AjaxResponse::I()->addError('you_cannot_edit_this_zone_because_server_is_not_active')->toArray();
  739. }
  740. try
  741. {
  742. $blockerHelper = new BlockerHelper();
  743. $isBlocked = false;
  744. if(!$blockerHelper->isLoggedUserExcluded()) {
  745. $rules = $blockerHelper->getRules();
  746. foreach($input['edit_record'] as $singleRecord){
  747. foreach($rules as $rule) {
  748. $rule = trim($rule);
  749. if($blockerHelper->isRecordBlocked($rule, $singleRecord['name'])) {
  750. $isBlocked = true;
  751. break;
  752. }
  753. }
  754. }
  755. }
  756. if($isBlocked) {
  757. return AjaxResponse::I()->addError('value_is_blocked')->toArray();
  758. }
  759. $module = $zone->getModule();
  760. $module->moduleConvertInputFormData($input);
  761. $oldRecords = RecordSetHelper::formatRecordsToIndexById($module->getRecords());
  762. if(!$module->customEditRecords($input))
  763. {
  764. foreach ($input['edit_record'] as $counter => $record_data)
  765. {
  766. $record = $this->createRecordFromInputData($record_data);
  767. $record->encode();
  768. $record->nameToAbsolute($zone->name);
  769. $module->editRecord($record);
  770. $editRecordHelper = new custom\helpers\ZoneLogger\Actions\EditRecord($record, $oldRecords[$record->line]);
  771. $zoneLoggerManager = new ZoneLoggerManager($_SESSION['uid']);
  772. $zoneLoggerManager->logEditRecordsInZone($zone, $editRecordHelper);
  773. }
  774. }
  775. }
  776. catch(Exception $exc)
  777. {
  778. LogHelper::addFailLogUsingZone('Edit Zone', $exc->getMessage(), $zone);
  779. throw $exc;
  780. }
  781. AjaxResponse::I()->addInfo('changes_saved');
  782. AjaxResponse::I()->refreshPage($this->editZoneHTML($input));
  783. return AjaxResponse::I()->toArray();
  784. }
  785. private function formatRecordsToIndexById($records = [])
  786. {
  787. $out = [];
  788. foreach ($records as $record)
  789. {
  790. $out[$record->line] = $record;
  791. }
  792. return $out;
  793. }
  794. private function getPTRLimits() {
  795. $helper = new ClientHelper($_SESSION['uid']);
  796. $groups = $helper->getGroups();
  797. $limit = 0;
  798. foreach($groups as $item) {
  799. $ptr = $this->getPTRLimitForGroup($item);
  800. if($ptr)
  801. {
  802. $limit += (int)$ptr * (int)$item[0]['zones_available'];
  803. }
  804. }
  805. return $limit;
  806. }
  807. private function getPTRLimitForGroup($group)
  808. {
  809. $relateditem = new RelatedItem($group[0]['type'], $group[0]['relid'], $_SESSION['uid']);
  810. $package = $relateditem->getPackage();
  811. if($package == false) {
  812. return FALSE;
  813. }
  814. $package_setting = unserialize($package->getSettings(PackageSettingEnum::ALLOWED_RECORD_TYPES));
  815. return $package_setting['PTR'];
  816. }
  817. private function countPTR() {
  818. return query::query("SELECT COUNT(*)
  819. FROM dns_manager2_reverse
  820. WHERE clientid = :userid",
  821. array('userid' => $_SESSION['uid']))->fetchColumn();
  822. // return query::query("SELECT COUNT(*)
  823. // FROM tblhosting
  824. // INNER JOIN dns_manager2_reverse ON dns_manager2_reverse.ip = tblhosting.dedicatedip OR tblhosting.assignedips LIKE CONCAT('%', dns_manager2_reverse.ip, '%')
  825. // WHERE userid = :userid AND domainstatus IN ('Active')
  826. // GROUP BY dns_manager2_reverse.id",
  827. // array('userid' => $_SESSION['uid']))->fetchColumn();
  828. }
  829. private function getUserPackageItems($userid) {
  830. $helper = new ClientHelper($userid);
  831. $groups = $helper->getGroups();
  832. $out = array();
  833. foreach($groups as $name => $group) {
  834. $ptr = $this->getPTRLimitForGroup($group);
  835. if(!$ptr)
  836. {
  837. continue;
  838. }
  839. $item = current($group);
  840. $out[] = array(
  841. 'name' => $name,
  842. 'type' => $item['type'],
  843. 'relid' => $item['relid']
  844. );
  845. }
  846. foreach($out as $k => $item) {
  847. $ip_array = IPHelper::getIPsArray($userid, $item['type'], $item['relid']);
  848. if(!IPHelper::isCustomIPEnabled()) {
  849. if((IPHelper::isSubnetCustomIPEnabled() && empty($ip_array['pools']) && empty($ip_array['all_ips']))
  850. || (!IPHelper::isSubnetCustomIPEnabled() && empty($ip_array['all_ips']))) {
  851. unset($out[$k]);
  852. }
  853. }
  854. }
  855. return $out;
  856. }
  857. public function generateLinks( $vars, $page, $limit )
  858. {
  859. $page++;
  860. $recordsCount = query::query("SELECT COUNT(id) AS recordsCount
  861. FROM dns_manager2_reverse
  862. WHERE clientid = :clientid",
  863. ['clientid' => $_SESSION['uid']])->fetch()['recordsCount'];
  864. $pages = ceil($recordsCount / $limit);
  865. if ( !$recordsCount || ceil($recordsCount / $limit) === 1 )
  866. {
  867. $vars['prev'] = 1;
  868. $vars['page'] = 1;
  869. $vars['next'] = 1;
  870. $vars['links'] = [];
  871. }
  872. else
  873. {
  874. $vars['prev'] = ($page - 1 > 0) ? $page - 1 : 1;
  875. $vars['page'] = $page;
  876. $vars['next'] = $page + 1 <= ceil($recordsCount / $limit) ? $page + 1 : ceil($recordsCount / $limit);
  877. $linksToBeDisplayed = 3;
  878. $rangeMin = $page - $linksToBeDisplayed > 0 ? $page - $linksToBeDisplayed : 0;
  879. $rangeMax = $page + $linksToBeDisplayed < $pages ? $page + $linksToBeDisplayed : $pages;
  880. $linksCount = 0;
  881. $start = floor($linksToBeDisplayed / 2);
  882. $start = ($page - $start) >= 1 ? $page-$start : 1 ;
  883. for ( $i = $start; $i <= $pages; $i++ )
  884. {
  885. if ( ($linksCount < $linksToBeDisplayed) && $i >= $rangeMin && $i <= $rangeMax )
  886. {
  887. $vars['links'][] = $i;
  888. $linksCount++;
  889. }
  890. }
  891. }
  892. return $vars;
  893. }
  894. public function manageRDNSHTML($input, $vars = array()) {
  895. $page = isset( $_GET['page']) && ((int)$_GET['page'] - 1) >= 0 ? (int)$_GET['page'] - 1 : 0;
  896. $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 15;
  897. $offset = $page * $limit;
  898. $vars = $this->generateLinks($vars, $page, $limit);
  899. $data = query::query("SELECT *
  900. FROM dns_manager2_reverse
  901. WHERE clientid = :clientid
  902. LIMIT :offset,:limit", ['clientid' => $_SESSION['uid'], 'offset' => $offset, 'limit' => $limit])->fetchAll();
  903. $vars['ptrs'] = $data;
  904. $vars['limit'] = $this->getPTRLimits();
  905. $vars['counter'] = 1;
  906. $query = htmlspecialchars_decode($_SERVER['QUERY_STRING']);
  907. $vars['query'] = 'index.php?'.preg_replace('/&page=\w+/', '', $query);
  908. return array(
  909. 'tpl' => 'manage-rdns'
  910. ,'vars' => $vars
  911. );
  912. }
  913. public function manageRDNSJSON($input, $vars = array()) {
  914. return AjaxResponse::I()->refreshPage($this->manageRDNSHTML($input))->toArray();
  915. }
  916. public function addRDNSJSON($input, $vars = array()) {
  917. $vars['items'] = $this->getUserPackageItems($_SESSION['uid']);
  918. return AjaxResponse::I()->modal('add-rdns', $vars)->toArray();
  919. }
  920. public function getRDNSDataJSON($input, $vars = array()) {
  921. $vars = IPHelper::getIPsArray($_SESSION['uid'], $input['type'], $input['relid']);
  922. foreach($vars['ips'] as $ip) {
  923. try {
  924. $relateditem = new RelatedItem($input['type'], $input['relid'], $_SESSION['uid']);
  925. $package = $relateditem->getPackage();
  926. if($package == false) {
  927. throw new Exception('No package found');
  928. }
  929. $server = $package->getFirstActiveServer();
  930. if($server == false) {
  931. throw new Exception('No active server related to this item');
  932. }
  933. if(reverse\Reverse::byServerIDAndIP($server->id, (string) $ip) !== false) {
  934. throw new Exception('IP already taken', 103);
  935. }
  936. }
  937. catch(Exception $e) {
  938. $vars['blocked_ips'][$ip] = $ip;
  939. }
  940. }
  941. $vars['any_pool'] = !empty($vars['pools']);
  942. $vars['custom_ip'] = IPHelper::isCustomIPEnabled();
  943. AjaxResponse::I()->html = main\mgLibs\smarty::I()->view('rdns-data',
  944. $vars,
  945. main\addon::getModuleTemplatesDir().DS.'pages' . DS . main\addon::I()->page);
  946. return AjaxResponse::I()->toArray();
  947. }
  948. public function addRDNSSaveJSON($input, $vars = array()) {
  949. $helper = new ClientHelper($_SESSION['uid']);
  950. list($type, $relid) = explode('::', $input['item']);
  951. $relateditem = new RelatedItem($type, $relid, $_SESSION['uid']);
  952. $package = $relateditem->getPackage();
  953. if($package == false) {
  954. return AjaxResponse::I()->addRawError('No package found')->toArray();
  955. }
  956. $server = $package->getFirstActiveServer();
  957. if($server == FALSE) {
  958. return AjaxResponse::I()->addError('no_active_server_related_to_this_item')->toArray();
  959. }
  960. $module = $server->getModule();
  961. if($server->getSettings(ServerSettingEnum::ALLOW_RDNS) != 'on' || !$module->isRDNSSupported()) {
  962. return AjaxResponse::I()->addError('rnds_disabled')->toArray();
  963. }
  964. try {
  965. $package_settings = unserialize($package->getSettings(PackageSettingEnum::ALLOWED_RECORD_TYPES));
  966. $ptrLimit = $package_settings['PTR'];
  967. $count = $this->countPTR();
  968. if($count >= $ptrLimit) {
  969. return AjaxResponse::I()->addError('you_cant_add_this_record_because_you_reach_limit')->toArray();
  970. }
  971. if(strpos($input['ip'], 'block') !== false) {
  972. list($str,$pool,$mask) = explode('|',$input['ip']);
  973. $ip = new IP($input['ip_from_block']);
  974. if(!$ip->isInNetwork($pool, $mask)) {
  975. return AjaxResponse::I()->addError('ip_is_not_belongs_to_selected_block')->toArray();
  976. }
  977. $input['ip'] = $input['ip_from_block'];
  978. }
  979. $ip = $input['ip'];
  980. $field = $input['field'];
  981. $rdata = isset($field['ptrdname']) ? $field['ptrdname'] : reset($field);
  982. $blockerHelper = new BlockerHelper();
  983. $isBlocked = false;
  984. if(!$blockerHelper->isLoggedUserExcluded()) {
  985. $rules = $blockerHelper->getRules(true);
  986. foreach($rules as $rule) {
  987. $rule = trim($rule);
  988. if($blockerHelper->isRecordBlocked($rule, $rdata)) {
  989. $isBlocked = true;
  990. break;
  991. }
  992. }
  993. }
  994. if($isBlocked) {
  995. return AjaxResponse::I()->addError('value_is_blocked')->toArray();
  996. }
  997. // $ip_array = IPHelper::getIPsArray($_SESSION['uid'], $type, $relid);
  998. // if(!in_array($ip, $ip_array['all_ips'])) {
  999. // return AjaxResponse::I()->addError('you_cant_use_ip_that_not_belongs_to_you')->toArray();
  1000. // }
  1001. IPHelper::validateIfClientCanUseIP($_SESSION['uid'], $type, $relid, $ip);
  1002. $reverse = new main\mgLibs\custom\reverse\ReverseDNS();
  1003. $reverse->setServer($server);
  1004. $reverse->setClientID($_SESSION['uid']);
  1005. $reverse->setIP($ip);
  1006. $reverse->setTTL($input['ttl']);
  1007. $reverse->setDomain($input['field']['ptrdname']);
  1008. $reverse->setType($type);
  1009. $reverse->setRelId($relid);
  1010. $reverse->create();
  1011. $zoneLogger = new ZoneLoggerManager($_SESSION['uid']);
  1012. $zoneLogger->logAddRdns($reverse);
  1013. AjaxResponse::I()->addInfo('new_record_added_to_zone');
  1014. return $this->manageRDNSJSON($input, $vars);
  1015. } catch (Exception $exc) {
  1016. return AjaxResponse::I()->addRawError($exc->getMessage())->toArray();
  1017. }
  1018. }
  1019. public function removeRDNSJSON($input, $vars = array()) {
  1020. $reverse = new reverse\Reverse($input['rid']);
  1021. if ($reverse->clientid != $_SESSION['uid']) {
  1022. return AjaxResponse::I()->addError('you_cannot_remove_record_that_is_not_belongs_to_you')->toArray();
  1023. }
  1024. try {
  1025. $helper = new main\mgLibs\custom\reverse\ReverseDNS($reverse);
  1026. $helper->remove();
  1027. } catch (Exception $e) {
  1028. return AjaxResponse::I()->addRawError($e->getMessage())->toArray();
  1029. }
  1030. AjaxResponse::I()->addInfo('record_removed_successfully');
  1031. AjaxResponse::I()->refreshPage($this->manageRDNSHTML($input));
  1032. return AjaxResponse::I()->toArray();
  1033. }
  1034. public function editRDNSJSON($input, $vars = array()) {
  1035. $reverse = new reverse\Reverse($input['rid']);
  1036. $vars['rdata'] = $reverse->getFullDomain();
  1037. $vars['rid'] = $input['rid'];
  1038. $vars['ee'] = isset($input['ee']);
  1039. return AjaxResponse::I()->modal('edit-rdns', $vars)->toArray();
  1040. }
  1041. public function editRDNSSaveJSON($input, $vars = array()) {
  1042. $reverse = new reverse\Reverse($input['rid']);
  1043. if ($reverse->clientid != $_SESSION['uid']) {
  1044. return AjaxResponse::I()->addRawError('...')->toArray();
  1045. }
  1046. try {
  1047. $rdata = $input['rdata'];
  1048. $blockerHelper = new BlockerHelper();
  1049. $isBlocked = false;
  1050. if(!$blockerHelper->isLoggedUserExcluded()) {
  1051. $rules = $blockerHelper->getRules(true);
  1052. foreach($rules as $rule) {
  1053. $rule = trim($rule);
  1054. if($blockerHelper->isRecordBlocked($rule, $rdata)) {
  1055. $isBlocked = true;
  1056. break;
  1057. }
  1058. }
  1059. }
  1060. if($isBlocked) {
  1061. return AjaxResponse::I()->addError('value_is_blocked')->toArray();
  1062. }
  1063. $helper = new main\mgLibs\custom\reverse\ReverseDNS($reverse);
  1064. $helper->setDomain($input['rdata']);
  1065. $helper->update();
  1066. } catch (Exception $e) {
  1067. return AjaxResponse::I()->addRawError($e->getMessage())->toArray();
  1068. }
  1069. return AjaxResponse::I()->refreshPage($this->manageRDNSHTML($input))->addInfo('RDNSchanged')->toArray();
  1070. }
  1071. public function dnsSecHTML($input, $vars = array())
  1072. {
  1073. $this->redirectIfIsOnlyRDNSforCA();
  1074. $helper = new ClientHelper($_SESSION['uid']);
  1075. $zone = new Zone($input['zone_id']);
  1076. $module = $zone->getModule();
  1077. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  1078. if(!$helper->isZoneOwnedByClient($zone))
  1079. {
  1080. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_it_is_not_belongs_to_you');
  1081. }
  1082. elseif(!$checkServer['status'])
  1083. {
  1084. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_server_is_not_active');
  1085. }
  1086. elseif(! ($zone->getServer()->getSettings(ServerSettingEnum::ENABLE_DNSSEC) == 'on' && $module->isDNSSECSupported()))
  1087. {
  1088. $vars['error'] = lang::T('dnssec_is_disabled');
  1089. }
  1090. else
  1091. {
  1092. if(!$module->zoneExists())
  1093. {
  1094. $vars['error'] = lang::T('you_cannot_edit_this_zone_because_it_is_terminated_on_server');
  1095. }
  1096. else
  1097. {
  1098. $vars['is_signed'] = $module->isSigned();
  1099. $vars['keys'] = array();
  1100. $keys = $module->getSignKeys();
  1101. if(method_exists($keys, 'hasKeys') && $keys->hasKeys())
  1102. {
  1103. $vars['keys']['keys'] = array_merge($keys->getKsk(), $keys->getCsk(), $keys->getZsk());
  1104. $vars['keys']['ds'] = $keys->getDs();
  1105. }
  1106. }
  1107. }
  1108. $vars['zone_name'] = $zone->name;
  1109. $vars['zoneid'] = $zone->id;
  1110. return array
  1111. (
  1112. 'tpl' => 'dnssec',
  1113. 'vars' => $vars
  1114. );
  1115. }
  1116. public function disableDnssecJSON($input, $vars = array())
  1117. {
  1118. $helper = new ClientHelper($_SESSION['uid']);
  1119. $zone = new Zone($input['zone_id']);
  1120. $module = $zone->getModule();
  1121. if(!$helper->isZoneOwnedByClient($zone))
  1122. {
  1123. return AjaxResponse::I()->addRawError(lang::T('you_cannot_edit_this_zone_because_it_is_not_belongs_to_you'))->toArray();
  1124. }
  1125. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  1126. if(!$checkServer['status'])
  1127. {
  1128. return AjaxResponse::I()->addRawError(lang::T('you_cannot_edit_this_zone_because_server_is_not_active'))->toArray();
  1129. }
  1130. if(! ($zone->getServer()->getSettings(ServerSettingEnum::ENABLE_DNSSEC) == 'on' && $module->isDNSSECSupported()))
  1131. {
  1132. return AjaxResponse::I()->addRawError(lang::T('dnssec_is_disabled'));
  1133. }
  1134. try
  1135. {
  1136. $module->unsign();
  1137. }
  1138. catch(Exception $e)
  1139. {
  1140. return AjaxResponse::I()->addRawError($e->getMessage())->toArray();
  1141. }
  1142. return AjaxResponse::I()->refreshPage($this->dnsSecHTML($input))->addInfo('DNSSECDisabledSuccess')->toArray();
  1143. }
  1144. public function enableDnssecJSON($input, $vars = array())
  1145. {
  1146. $helper = new ClientHelper($_SESSION['uid']);
  1147. $zone = new Zone($input['zone_id']);
  1148. $module = $zone->getModule();
  1149. if(!$helper->isZoneOwnedByClient($zone))
  1150. {
  1151. return AjaxResponse::I()->addRawError(lang::T('you_cannot_edit_this_zone_because_it_is_not_belongs_to_you'))->toArray();
  1152. }
  1153. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  1154. if(!$checkServer['status'])
  1155. {
  1156. return AjaxResponse::I()->addRawError(lang::T('you_cannot_edit_this_zone_because_server_is_not_active'))->toArray();
  1157. }
  1158. if(! ($zone->getServer()->getSettings(ServerSettingEnum::ENABLE_DNSSEC) == 'on' && $module->isDNSSECSupported()))
  1159. {
  1160. return AjaxResponse::I()->addRawError(lang::T('dnssec_is_disabled'));
  1161. }
  1162. try
  1163. {
  1164. $module->sign();
  1165. }
  1166. catch(Exception $e)
  1167. {
  1168. return AjaxResponse::I()->addRawError($e->getMessage())->toArray();
  1169. }
  1170. return AjaxResponse::I()->refreshPage($this->dnsSecHTML($input))->addInfo('DNSSECEnableSuccess')->toArray();
  1171. }
  1172. public function rectifyDnssecJSON($input, $vars = array())
  1173. {
  1174. $helper = new ClientHelper($_SESSION['uid']);
  1175. $zone = new Zone($input['zone_id']);
  1176. $module = $zone->getModule();
  1177. if(!$helper->isZoneOwnedByClient($zone))
  1178. {
  1179. return AjaxResponse::I()->addRawError(lang::T('you_cannot_edit_this_zone_because_it_is_not_belongs_to_you'))->toArray();
  1180. }
  1181. $checkServer = $helper::getServerStatusByZoneId($zone->id);
  1182. if(!$checkServer['status'])
  1183. {
  1184. return AjaxResponse::I()->addRawError(lang::T('you_cannot_edit_this_zone_because_server_is_not_active'))->toArray();
  1185. }
  1186. if(! ($zone->getServer()->getSettings(ServerSettingEnum::ENABLE_DNSSEC) == 'on' && $module->isDNSSECSupported()))
  1187. {
  1188. return AjaxResponse::I()->addRawError(lang::T('dnssec_is_disabled'));
  1189. }
  1190. try
  1191. {
  1192. $module->rectify();
  1193. }
  1194. catch(Exception $e)
  1195. {
  1196. return AjaxResponse::I()->addRawError($e->getMessage())->toArray();
  1197. }
  1198. return AjaxResponse::I()->refreshPage($this->dnsSecHTML($input))->addInfo('DNSSECRectifySuccess')->toArray();
  1199. }
  1200. public function arraySortByValue($key)
  1201. {
  1202. return function ($obA, $obB) use ($key)
  1203. {
  1204. return strnatcmp($obA->$key, $obB->$key);
  1205. };
  1206. }
  1207. /* DNS Sets */
  1208. public function listJSON($input, $vars = array())
  1209. {
  1210. $query = "SELECT dns_manager2_set.id AS id, dns_manager2_set.default AS def, dns_manager2_set.idu AS idu, dns_manager2_set.name AS name, COUNT(DISTINCT(dns_manager2_setrecord.id)) AS dnsrecords
  1211. FROM dns_manager2_set
  1212. LEFT JOIN dns_manager2_setrecord ON dns_manager2_setrecord.setid = dns_manager2_set.id
  1213. LEFT JOIN dns_manager2_packageset ON dns_manager2_packageset.setid = dns_manager2_set.id
  1214. LEFT JOIN dns_manager2_package ON dns_manager2_package.defaultset = dns_manager2_set.id
  1215. WHERE idu = ".$_SESSION['uid']."
  1216. GROUP BY dns_manager2_set.id";
  1217. $columns = array('name','dnsrecords','idu','def');
  1218. $helper = new main\mgLibs\custom\RawQueryTableHelper($query, $input, $columns);
  1219. $vars = $helper->getDataTableArray();
  1220. foreach($helper->get() as $set)
  1221. {
  1222. $vars['data'][] = $this->dataTablesParseRow('set-row', array('set' => $set));
  1223. }
  1224. return $vars;
  1225. }
  1226. public function addSetJSON($input, $vars = array())
  1227. {
  1228. $vars['set'] = $this->set_form;
  1229. $vars['available_record_types'] = main\mgLibs\custom\dns\Core::getAvailableRecordTypesByActiveServers();
  1230. return AjaxResponse::I()->modal('set-edit', $vars)->toArray();
  1231. }
  1232. public function addNewRecordJSON($input, $vars = array())
  1233. {
  1234. $class = 'MGModule\DNSManager2\mgLibs\custom\dns\record\type\\' . $input['new_record_type'];
  1235. if(class_exists($class))
  1236. {
  1237. $vars['counter'] = $input['records_counter'];
  1238. $vars['record_type'] = $input['new_record_type'];
  1239. $vars['record_obj'] = new $class();
  1240. $vars['record_fields'] = get_object_vars($vars['record_obj']);
  1241. AjaxResponse::I()->new_record = main\mgLibs\smarty::I()->view('new-record',
  1242. $vars,
  1243. main\addon::getModuleTemplatesDir().DS.'pages' . DS . main\addon::I()->page);
  1244. }
  1245. else
  1246. {
  1247. AjaxResponse::I()->addError('cannot_find_class', array('class' => $class));
  1248. }
  1249. return AjaxResponse::I()->toArray();
  1250. }
  1251. public function duplicateSetJSON($input, $vars = array()) {
  1252. $set = new set\Set($input['id']);
  1253. $vars['set']['id'] = $set->id;
  1254. $vars['set']['name'] = $set->name.' Duplication';
  1255. return AjaxResponse::I()->modal('set-duplicate', $vars)->toArray();
  1256. }
  1257. public function setDuplicateJSON($input, $vars = array()) {
  1258. $duplicatedSet = new set\Set($input['id']);
  1259. $newSet = new set\Set(false);
  1260. $newSet->name = $input['name'];
  1261. $newSet->idu = $duplicatedSet->idu;
  1262. $newSet->save();
  1263. foreach($duplicatedSet->getRecords() as $record_data) {
  1264. $newSet->setRecord($record_data->name, $record_data->type, $record_data->ttl, $record_data->rdata, false);
  1265. }
  1266. AjaxResponse::I()->addInfo('changes_saved');
  1267. return AjaxResponse::I()->toArray();
  1268. }
  1269. public function editSetJSON($input, $vars = array())
  1270. {
  1271. $set = new main\models\custom\set\Set($input['id']);
  1272. $vars['set'] = $this->set_form;
  1273. $vars['set']['edit'] = true;
  1274. $vars['set']['id'] = $set->id;
  1275. $vars['set']['name'] = $set->name;
  1276. $vars['set']['default'] = $set->default;
  1277. $vars['set']['records'] = $set->getRecords();
  1278. $vars['set']['count'] = count($vars['set']['records']);
  1279. $vars['counter'] = 0;
  1280. $vars['available_record_types'] = main\mgLibs\custom\dns\Core::getAvailableRecordTypesByActiveServers();
  1281. return AjaxResponse::I()->modal('set-edit', $vars)->toArray();
  1282. }
  1283. public function setSaveJSON($input, $vars = array())
  1284. {
  1285. if($input['default'] == '1')
  1286. {
  1287. $user_sets = main\mgLibs\MySQL\query::select(array('id','name','idu','default'), 'dns_manager2_set', array('idu' => $_SESSION['uid']))->fetchAll();
  1288. foreach($user_sets as $u)
  1289. {
  1290. main\mgLibs\MySQL\query::update('dns_manager2_set', array('default' => ''), array('idu' => $_SESSION['uid']));
  1291. }
  1292. }
  1293. $blockerHelper = new BlockerHelper();
  1294. $isBlocked = false;
  1295. if(!$blockerHelper->isLoggedUserExcluded()) {
  1296. $rules = $blockerHelper->getRules();
  1297. foreach($input['record'] as $singleRecord){
  1298. foreach($rules as $rule) {
  1299. $rule = trim($rule);
  1300. if($blockerHelper->isRecordBlocked($rule, $singleRecord['name'])) {
  1301. $isBlocked = true;
  1302. break;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. if($isBlocked) {
  1308. return AjaxResponse::I()->addError('value_is_blocked')->toArray();
  1309. }
  1310. $set = new main\models\custom\set\Set($input['id']?:false);
  1311. $set->name = $input['name'];
  1312. $set->idu = $_SESSION['uid'];
  1313. $set->default = $input['default'];
  1314. $set->save();
  1315. foreach($input['record'] as $record_data)
  1316. {
  1317. $set->setRecord($record_data['name'], $record_data['type'], $record_data['ttl'], $record_data['field'], $record_data['id']?:false);
  1318. }
  1319. foreach($input['remove_record'] as $id)
  1320. {
  1321. $record = new main\models\custom\set\record\SetRecord($id);
  1322. $record->delete();
  1323. }
  1324. AjaxResponse::I()->addInfo('dns_record_added_successfully');
  1325. return AjaxResponse::I()->toArray();
  1326. }
  1327. public function removeSetJSON($input, $vars = array())
  1328. {
  1329. main\models\custom\set\Set::factory($input['id'])->delete();
  1330. return AjaxResponse::I()->addInfo('set_removed')->toArray();
  1331. }
  1332. private function getClientSets()
  1333. {
  1334. $clientSets = set\Repository::factory()->byUserId((int)$_SESSION['uid'])->get();
  1335. return $clientSets;
  1336. }
  1337. private function getDefaultSet()
  1338. {
  1339. $default = set\Repository::factory()->byUserId((int)$_SESSION['uid'])->setFilter('default',1)->get();
  1340. return $default[0]->id;
  1341. }
  1342. public function setRecordsJSON($input, $vars = array())
  1343. {
  1344. if(!array_filter($input['zone']['checked']))
  1345. {
  1346. return AjaxResponse::I()->addError('select_one_at_least')->toArray();
  1347. }
  1348. $vars['sets'] = $this->getClientSets();
  1349. return AjaxResponse::I()->modal('set-records', $vars)->toArray();
  1350. }
  1351. public function exportFromFileJSON($input, $vars = array())
  1352. {
  1353. $vars['exportId'] = $input['id'];
  1354. AjaxResponse::I()->refreshPage(array('tpl' => 'export-list', 'vars' => $vars));
  1355. return AjaxResponse::I()->toArray();
  1356. }
  1357. public function exportZonesJSON($input, $vars = array())
  1358. {
  1359. $add = false;
  1360. $exported = false;
  1361. foreach($input['zone'] as $result_id => $data)
  1362. {
  1363. if($data['export'] != 'on' && !isset($input['justOne']))
  1364. {
  1365. continue;
  1366. }
  1367. $exported = true;
  1368. $result = new task\result\TaskResult($result_id);
  1369. $task = custom\TaskManager::getTaskObjectByID($result->taskid);
  1370. $main_task = $task->getParent(); //TODO: można zmniejszyć ilość danych poprzez odwołanie się do resulta
  1371. $result->data['resultid'] = $result_id;
  1372. $child = $main_task->addChild('export', $result->data);
  1373. $result->data['status'] = 'exporting';
  1374. $result->data['taskid'] = $child->obj()->id;
  1375. $result->save();
  1376. if(isset($input['runNow']))
  1377. {
  1378. $child->run();
  1379. if($child->getStatus() !== 'finished')
  1380. {
  1381. AjaxResponse::I()->addError('something_went_wrong_during_import');
  1382. }
  1383. else
  1384. {
  1385. AjaxResponse::I()->addInfo('zone_imported');
  1386. }
  1387. }
  1388. else
  1389. {
  1390. if($add === false)
  1391. {
  1392. AjaxResponse::I()->addInfo('new_task_added');
  1393. $add = true;
  1394. }
  1395. }
  1396. }
  1397. if(!$exported)
  1398. {
  1399. AjaxResponse::I()->addError('no_zone_selected_for_import_export');
  1400. }
  1401. return AjaxResponse::I()->toArray();
  1402. }
  1403. function refreshExportTableJSON($input, $vars = array())
  1404. {
  1405. $pRep = task\Repository::factory()->byParentID($input['id'])->one();
  1406. $pRepName = explode(':', $pRep->name);
  1407. $task = custom\TaskManager::getXTasks(1, $pRepName[0].':fetchZonesList', $input['id'], false);
  1408. $task = end($task);
  1409. $rep = task\result\Repository::factory()->byTaskID($task->id);
  1410. $helper = new main\mgLibs\custom\RepoTableHelper($rep, $input, array('data'));
  1411. $vars = $helper->getDataTableArray();
  1412. $whmcsZones = query::query('SELECT name, id FROM dns_manager2_zone')->fetchGroup();
  1413. foreach($helper->get() as $task)
  1414. {
  1415. if(!isset($whmcsZones[$task->data['domain']]))
  1416. {
  1417. $task->data['status'] = 'notExistInWhmcs';
  1418. }
  1419. $vars['data'][] = $this->dataTablesParseRow('export-row',
  1420. array(
  1421. 'item' => $task,
  1422. 'exportId' => $input['id'],
  1423. )
  1424. );
  1425. }
  1426. return $vars;
  1427. }
  1428. public function backupsHTML($input, $vars = array())
  1429. {
  1430. if(GlobalSettingHelper::getSetting(GlobalSettingEnum::LINK_TO_CLIENTAREA_IMPORT_EXPORT, true) != 'on')
  1431. {
  1432. redir('m=DNSManager2');
  1433. }
  1434. $this->redirectIfIsOnlyRDNSforCA();
  1435. $vars['backupsTasks'] = $this->getImportToFileClientTasks();
  1436. $newImportsToFile = custom\TaskManager::getXTasksObjects(0, 'ExportFromFileWHMCS:main', 0, task\TaskStatusEnum::START, $_SESSION['uid']);
  1437. $this->parseNewImportTaskList($newImportsToFile, $vars['backupsTasks']);
  1438. $toFileImports = custom\TaskManager::getXTasksObjects(0, 'ExportFromFileWHMCS:main', 0, task\TaskStatusEnum::IN_PROGRESS, $_SESSION['uid']);
  1439. $this->parseInProgresImportTaskList($toFileImports, $vars['backupsTasks'], 'ExportFromFileWHMCS', $_SESSION['uid']);
  1440. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones');
  1441. $filesList = main\mgLibs\custom\helpers\ImportExportFileHelper::listFilesForBulkExport($fileManager, false);
  1442. $manualFilesList = ClientFilesManage::getManualBackups($_SESSION['uid'], $filesList, ClientFilesManage::BACKUP);
  1443. $cronFilesList = ClientFilesManage::getCronBackups($_SESSION['uid'], $filesList, ClientFilesManage::BACKUP);
  1444. $amountOfManualBackups = count($manualFilesList);
  1445. $amountOfCronBackups = count($cronFilesList);
  1446. $manualBackupsLimit = GlobalSettingHelper::getSetting(GlobalSettingEnum::CLIENTAREA_IMPORT_EXPORT_LIMIT);
  1447. $cronBackupsLimit = GlobalSettingHelper::getSetting(GlobalSettingEnum::CRON_BACKUP_LIMIT);
  1448. $manualBackupsLimit = $manualBackupsLimit != -1 ? $manualBackupsLimit : '∞';
  1449. $cronBackupsLimit = $cronBackupsLimit != -1 ? $cronBackupsLimit : '∞';
  1450. if($manualBackupsLimit != 0)
  1451. {
  1452. $vars['manualBackupLimitDisplay'] = "({$amountOfManualBackups}/{$manualBackupsLimit})";
  1453. }
  1454. if($cronBackupsLimit != 0)
  1455. {
  1456. $vars['cronBackupLimitDisplay'] = "({$amountOfCronBackups}/{$cronBackupsLimit})";
  1457. }
  1458. $vars['caCanAddBackup'] = $this->canAddBackup();
  1459. return array(
  1460. 'tpl' => 'backups',
  1461. 'vars' => $vars
  1462. );
  1463. }
  1464. private function getImportToFileClientTasks()
  1465. {
  1466. $vars = array();
  1467. $waitingImportsToFile = custom\TaskManager::getXTasksObjects(0, 'ImportToFileWHMCS:main', 0, task\TaskStatusEnum::WAITING, $_SESSION['uid']);
  1468. $this->parseNewImportTaskList($waitingImportsToFile, $vars);
  1469. $newImportsToFile = custom\TaskManager::getXTasksObjects(0, 'ImportToFileWHMCS:main', 0, task\TaskStatusEnum::START, $_SESSION['uid']);
  1470. $this->parseNewImportTaskList($newImportsToFile, $vars);
  1471. $toFileImports = custom\TaskManager::getXTasksObjects(0, 'ImportToFileWHMCS:main', 0, task\TaskStatusEnum::IN_PROGRESS, $_SESSION['uid']);
  1472. $this->parseInProgresImportTaskList($toFileImports, $vars, 'ImportToFileWHMCS', $_SESSION['uid']);
  1473. return $vars;
  1474. }
  1475. private function canAddBackup()
  1476. {
  1477. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones');
  1478. $filesList = main\mgLibs\custom\helpers\ImportExportFileHelper::listFilesForBulkExport($fileManager, false);
  1479. $filesList = ClientFilesManage::getFilesForClient($_SESSION['uid'], $filesList, ClientFilesManage::BACKUP);
  1480. $taskImport = $this->getImportToFileClientTasks();
  1481. $amountOfBackups = count($filesList) + count($taskImport);
  1482. $limit = GlobalSettingHelper::getSetting(GlobalSettingEnum::CLIENTAREA_IMPORT_EXPORT_LIMIT);
  1483. if($limit <= $amountOfBackups && $limit != -1)
  1484. {
  1485. return false;
  1486. }
  1487. return true;
  1488. }
  1489. public function uploadBackupFileJSON($input, $vars = array())
  1490. {
  1491. if(!$this->canAddBackup())
  1492. {
  1493. AjaxResponse::I()->addError('backups_limit_reached');
  1494. return AjaxResponse::I()->toArray();
  1495. }
  1496. $fileName = main\mgLibs\custom\FileManager::removeFakePath($input['fileName']);
  1497. if(!main\mgLibs\custom\FileManager::checkIfFileWasSent($fileName))
  1498. {
  1499. AjaxResponse::I()-> addError('sendingFailed', array('file' => $fileName));
  1500. return AjaxResponse::I()->toArray();
  1501. }
  1502. $type = main\mgLibs\custom\FileManager::checkTypeByContent($fileName);
  1503. if($type !== 'single' && $type !== 'bulk')
  1504. {
  1505. AjaxResponse::I()->addError('invalidContent', array('file' => $fileName));
  1506. return AjaxResponse::I()->toArray();
  1507. }
  1508. $explodedFileName = explode('_', $fileName);
  1509. $clientId = $explodedFileName[count($explodedFileName)-1];
  1510. if($clientId != $_SESSION['uid'])
  1511. {
  1512. $newfileName = custom\helpers\ImportExportFileHelper::generateClientFileName($_SESSION['uid']);
  1513. foreach ($_FILES as &$file)
  1514. {
  1515. if($file['name'] == $fileName)
  1516. {
  1517. $file['name'] = $newfileName;
  1518. $fileName = $newfileName;
  1519. }
  1520. }
  1521. }
  1522. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.$type.'Zones');
  1523. if(!$fileManager->isStorageReadable() || !$fileManager->isStorageWritable())
  1524. {
  1525. AjaxResponse::I()-> addError('directoryPermissionWritableReadable', array('storageDir' => $fileManager->getStoragePath()));
  1526. return AjaxResponse::I()->toArray();
  1527. }
  1528. if($fileManager->fileExists($fileName))
  1529. {
  1530. AjaxResponse::I()->addError('fileAlreadyExist', array('file' => $fileName));
  1531. return AjaxResponse::I()->toArray();
  1532. }
  1533. if($fileManager->uploadFile($fileName))
  1534. {
  1535. ClientFilesManage::save($fileName, $_SESSION['uid'], ClientFilesManage::BACKUP, 'client');
  1536. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1537. AjaxResponse::I()->addInfo('uploadSuccesfull');
  1538. return AjaxResponse::I()->toArray();
  1539. }
  1540. if(!main\mgLibs\custom\FileManager::checkIfFileWasSent($fileName))
  1541. {
  1542. AjaxResponse::I()-> addError('sendingFailed', array('file' => $fileName));
  1543. return AjaxResponse::I()->toArray();
  1544. }
  1545. }
  1546. private function sortBackupFiles(&$filesList, $order)
  1547. {
  1548. if($order)
  1549. {
  1550. rsort($filesList);
  1551. return;
  1552. }
  1553. sort($filesList);
  1554. }
  1555. private function sortBackupFilesByZonesNumber(&$filesList, $order)
  1556. {
  1557. if($order)
  1558. {
  1559. arsort($filesList);
  1560. return;
  1561. }
  1562. asort($filesList);
  1563. }
  1564. public function refreshBackupsTableJSON($input, $vars = array())
  1565. {
  1566. $vars['data'] = array();
  1567. $vars['recordsTotal'] = 0;
  1568. $vars['recordsFiltered'] = 0;
  1569. $order = $input['order']['dir'] == 'desc' ? 1 : 0;
  1570. $columnName = $input['order']['column'];
  1571. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones');
  1572. $filesList = main\mgLibs\custom\helpers\ImportExportFileHelper::listFilesForBulkExport($fileManager, false, $order);
  1573. $filesList = ClientFilesManage::getManualBackups($_SESSION['uid'], $filesList, ClientFilesManage::BACKUP);
  1574. if($columnName == 'name')
  1575. {
  1576. $this->sortBackupFiles($filesList, $order);
  1577. } elseif($columnName == 'type')
  1578. {
  1579. $newFilesList = [];
  1580. foreach($filesList as $fileName)
  1581. {
  1582. $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones', $fileName.'_'.$_SESSION['uid']);
  1583. $newFilesList[$fileName] = count((array)$backupZone);
  1584. }
  1585. $this->sortBackupFilesByZonesNumber($newFilesList, $order);
  1586. $filesList = array_keys($newFilesList);
  1587. }
  1588. foreach($filesList as $fileName)
  1589. {
  1590. $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones', $fileName.'_'.$_SESSION['uid']);
  1591. $vars['recordsTotal']++;
  1592. if($input['search'] && $this->isFilenameMatch($fileName, $input['search']))
  1593. {
  1594. $vars['data'][] = $this->dataTablesParseRow('backup-row', array('fileName' => $fileName, 'type' => 'bulk', 'zonesAmount' => count((array)$backupZone)));
  1595. $vars['recordsFiltered']++;
  1596. }
  1597. elseif(!$input['search'])
  1598. {
  1599. $vars['data'][] = $this->dataTablesParseRow('backup-row', array('fileName' => $fileName, 'type' => 'bulk', 'zonesAmount' => count((array)$backupZone)));
  1600. }
  1601. }
  1602. $vars['recordsFiltered'] = $input['search'] ? $vars['recordsFiltered'] : $vars['recordsTotal'];
  1603. $limit = $input['limit'];
  1604. $offset = $input['offset'];
  1605. $vars['data'] = array_slice($vars['data'], $offset, $limit);
  1606. return $vars;
  1607. }
  1608. public function refreshCronBackupsTableJSON($input, $vars = array())
  1609. {
  1610. $vars['data'] = array();
  1611. $vars['recordsTotal'] = 0;
  1612. $vars['recordsFiltered'] = 0;
  1613. $order = $input['order']['dir'] == 'desc' ? 1 : 0;
  1614. $columnName = $input['order']['column'];
  1615. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones');
  1616. $filesList = main\mgLibs\custom\helpers\ImportExportFileHelper::listFilesForBulkExport($fileManager, false, $order);
  1617. $filesList = ClientFilesManage::getCronBackups($_SESSION['uid'], $filesList, ClientFilesManage::BACKUP);
  1618. if($columnName == 'name')
  1619. {
  1620. $this->sortBackupFiles($filesList, $order);
  1621. } elseif($columnName == 'type')
  1622. {
  1623. $newFilesList = [];
  1624. foreach($filesList as $fileName)
  1625. {
  1626. $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones', $fileName.'_'.$_SESSION['uid']);
  1627. $newFilesList[$fileName] = count((array)$backupZone);
  1628. }
  1629. $this->sortBackupFilesByZonesNumber($newFilesList, $order);
  1630. $filesList = array_keys($newFilesList);
  1631. }
  1632. foreach($filesList as $fileName)
  1633. {
  1634. $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones', $fileName.'_'.$_SESSION['uid']);
  1635. $vars['recordsTotal']++;
  1636. if($input['search'] && $this->isFilenameMatch($fileName, $input['search']))
  1637. {
  1638. $vars['data'][] = $this->dataTablesParseRow('cron-backup-row', array('fileName' => $fileName, 'type' => 'bulk', 'zonesAmount' => count((array)$backupZone)));
  1639. $vars['recordsFiltered']++;
  1640. }
  1641. elseif(!$input['search'])
  1642. {
  1643. $vars['data'][] = $this->dataTablesParseRow('cron-backup-row', array('fileName' => $fileName, 'type' => 'bulk', 'zonesAmount' => count((array)$backupZone)));
  1644. }
  1645. }
  1646. $vars['recordsFiltered'] = $input['search'] ? $vars['recordsFiltered'] : $vars['recordsTotal'];
  1647. $limit = $input['limit'];
  1648. $offset = $input['offset'];
  1649. $vars['data'] = array_slice($vars['data'], $offset, $limit);
  1650. return $vars;
  1651. }
  1652. private function isFilenameMatch($fileName, $search)
  1653. {
  1654. if(strpos($fileName, $search) || strpos($fileName, $search) === 0)
  1655. {
  1656. return true;
  1657. }
  1658. return false;
  1659. }
  1660. public function removeBackupFileJSON($input, $vars = array())
  1661. {
  1662. $type = $input['type'];
  1663. $fileName = $input['id'] . '_' . $_SESSION['uid'];
  1664. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.$type.'Zones');
  1665. $exist = true;
  1666. if(!$fileManager->fileExists($fileName))
  1667. {
  1668. $exist = false;
  1669. // AjaxResponse::I()-> addError('fileDoesNotExist', array('file' => $fileName));
  1670. // return AjaxResponse::I()->toArray();
  1671. }
  1672. if(!$exist)
  1673. {
  1674. ClientFilesManage::delete($_SESSION['uid'], $fileName, ClientFilesManage::BACKUP);
  1675. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1676. AjaxResponse::I()->addInfo('fileRemoved');
  1677. return AjaxResponse::I()->toArray();
  1678. }
  1679. if($fileManager->deleteFile($fileName) && $exist)
  1680. {
  1681. ClientFilesManage::delete($_SESSION['uid'], $fileName, ClientFilesManage::BACKUP);
  1682. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1683. AjaxResponse::I()->addInfo('fileRemoved');
  1684. return AjaxResponse::I()->toArray();
  1685. }
  1686. AjaxResponse::I()-> addError('fileDeleteFailed', array('file' => $fileName));
  1687. return AjaxResponse::I()->toArray();
  1688. }
  1689. public function backupScheduleImportJSON($input, $vars = array())
  1690. {
  1691. custom\TaskManager::getTaskObjectByID($input['id'])->run(true);
  1692. AjaxResponse::I()->addInfo('import_scheduled');
  1693. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1694. return AjaxResponse::I()->toArray();
  1695. }
  1696. public function backupRemoveTaskJSON($input, $vars = array())
  1697. {
  1698. custom\TaskManager::removeTask($input['id']);
  1699. ClientFilesManage::delete($_SESSION['uid'], $input['file'], ClientFilesManage::FROM_FILE_TO_WHMCS);
  1700. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1701. AjaxResponse::I()->addInfo('taskRemoved');
  1702. return AjaxResponse::I()->toArray();
  1703. }
  1704. public function downloandBackupFileHTML($input, $vars = array())
  1705. {
  1706. $this->redirectIfIsOnlyRDNSforCA();
  1707. $filePatch = $_GET['path'];
  1708. if(!strpos($filePatch, 'DNSManager2'.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'zonesFilesStorage'))
  1709. {
  1710. $filePatch = false;
  1711. }
  1712. ob_clean();
  1713. header('Content-Description: File Transfer');
  1714. header('Content-Type: application/octet-stream');
  1715. header('Content-Disposition: attachment; filename="'.basename($filePatch).'"');
  1716. header('Expires: 0');
  1717. header('Cache-Control: must-revalidate');
  1718. header('Pragma: public');
  1719. header('Content-Length: '.filesize($filePatch));
  1720. readfile($filePatch);
  1721. die();
  1722. }
  1723. public function showBackupZonesJSON($input, $vars = array())
  1724. {
  1725. $fileName = $input['id'];
  1726. $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones', $fileName.'_'.$_SESSION['uid']);
  1727. AjaxResponse::I()->result = $backupZone;
  1728. return AjaxResponse::I()->toArray();
  1729. }
  1730. public function showCronBackupZonesJSON($input, $vars = array())
  1731. {
  1732. $fileName = $input['id'];
  1733. $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones', $fileName.'_'.$_SESSION['uid']);
  1734. AjaxResponse::I()->result = $backupZone;
  1735. return AjaxResponse::I()->toArray();
  1736. }
  1737. public function downloandBackupFileJSON($input, $vars = array())
  1738. {
  1739. $type = $input['type'];
  1740. $fileName = $input['id'] . '_' . $_SESSION['uid'];
  1741. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.$type.'Zones');
  1742. if(!$fileManager->fileExists($fileName))
  1743. {
  1744. AjaxResponse::I()-> addError('fileDoesNotExist', array('file' => $fileName));
  1745. return AjaxResponse::I()->toArray();
  1746. }
  1747. $filePatch = $fileManager->getStoragePath().$fileName;
  1748. $url = html_entity_decode(str_replace('mg-action=backups', 'mg-action=downloandBackupFile', $_SERVER['HTTP_REFERER']));
  1749. return array('seturlto' => $url.'&path='.$filePatch);
  1750. }
  1751. public function addExportSaveJSON($input, $vars = array())
  1752. {
  1753. $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'bulkZones');
  1754. $fileName = $input['id'] . '_' . $_SESSION['uid'];
  1755. $vars['isReadable'] = $fileManager->isStorageReadable();
  1756. if(!$vars['isReadable'])
  1757. {
  1758. AjaxResponse::I()->addError('pathInNotReadAble');
  1759. return AjaxResponse::I()->toArray();
  1760. }
  1761. $vars['storagePath'] = $fileManager->getStoragePath();
  1762. if(!$vars['storagePath'])
  1763. {
  1764. AjaxResponse::I()->addError('storageNotExists');
  1765. return AjaxResponse::I()->toArray();
  1766. }
  1767. $res = ClientFilesManage::saveIfNotExists($fileName, $_SESSION['uid'], ClientFilesManage::FROM_FILE_TO_WHMCS, 'client');
  1768. if(!$res)
  1769. {
  1770. AjaxResponse::I()->addError('exportFromThisFileExist');
  1771. return AjaxResponse::I()->toArray();
  1772. }
  1773. $task = custom\TaskManager::addTask('ExportFromFileWHMCS:main', array('fromFile' => $fileName), 0, $_SESSION['uid']);
  1774. custom\TaskManager::getTaskObjectByID($task->id)->run(true);
  1775. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1776. AjaxResponse::I()->addInfo('new_task_added');
  1777. return AjaxResponse::I()->toArray();
  1778. }
  1779. public function importZonesJSON($input, $vars = array())
  1780. {
  1781. $add = false;
  1782. $imported = false;
  1783. foreach($input['zone'] as $resultId => $data)
  1784. {
  1785. if($data['import'] != 'on' && !isset($input['justOne']))
  1786. {
  1787. continue;
  1788. }
  1789. $imported = true;
  1790. $task = new task\Task($input['id']);
  1791. $task->status = task\TaskStatusEnum::IN_PROGRESS;
  1792. $task->save();
  1793. $result = new task\result\TaskResult($resultId);
  1794. $task = custom\TaskManager::getTaskObjectByID($result->taskid);
  1795. $main_task = $task->getParent();
  1796. $result->data['resultid'] = $resultId;
  1797. $result->data['domain'] = custom\helpers\IdnaHelper::idnaDecode($result->data['name']);
  1798. $child = $main_task->addChild('import', $result->data);
  1799. $result->data['status'] = 'importing';
  1800. $result->data['taskid'] = $child->obj()->id;
  1801. $result->save();
  1802. if(isset($input['runNow']))
  1803. {
  1804. $child->run();
  1805. if($child->getStatus() !== 'finished')
  1806. {
  1807. AjaxResponse::I()->addError('something_went_wrong_during_import');
  1808. }
  1809. else
  1810. {
  1811. AjaxResponse::I()->addInfo('zone_imported');
  1812. }
  1813. }
  1814. else
  1815. {
  1816. if($add === false)
  1817. {
  1818. AjaxResponse::I()->addInfo('zonesUpdated');
  1819. $add = true;
  1820. }
  1821. }
  1822. }
  1823. if(!$imported)
  1824. {
  1825. AjaxResponse::I()->addError('no_zone_selected_for_import_export');
  1826. }
  1827. return AjaxResponse::I()->toArray();
  1828. }
  1829. public function importJSON($input, $vars = array()) {
  1830. return AjaxResponse::I()->refreshPage($this->importHTML($input, $vars))->toArray();
  1831. }
  1832. function refreshImportTableJSON($input, $vars = array())
  1833. {
  1834. $pRep = task\Repository::factory()->byParentID($input['id'])->one();
  1835. $pRepName = explode(':', $pRep->name);
  1836. $task = custom\TaskManager::getXTasks(1, $pRepName[0].':fetchZonesList', $input['id'], false);
  1837. $task = end($task);
  1838. $rep = task\result\Repository::factory()->byTaskID($task->id);
  1839. $input['limit'] = $rep->count();
  1840. $helper = new main\mgLibs\custom\RepoTableHelper($rep, $input, array('data'));
  1841. $vars = $helper->getDataTableArray();
  1842. foreach($helper->get() as $task)
  1843. {
  1844. $relid = $task->data['relid'];
  1845. if($relid != '0')
  1846. {
  1847. try
  1848. {
  1849. switch($task->data['type']) {
  1850. case '1':
  1851. $status = new main\models\whmcs\domains\domain($relid);
  1852. break;
  1853. case '2':
  1854. $status = new main\models\whmcs\service\service($relid);
  1855. break;
  1856. }
  1857. }
  1858. catch (\Exception $e)
  1859. {
  1860. continue;
  1861. }
  1862. if(!$status || $status->status() != 'Active')
  1863. continue;
  1864. }
  1865. $vars['data'][] = $this->dataTablesParseRow('import-row',
  1866. array(
  1867. 'item' => $task,
  1868. 'importid' => $input['id'],
  1869. )
  1870. );
  1871. }
  1872. return $vars;
  1873. }
  1874. public function showListImportToFileJSON($input, $vars = array())
  1875. {
  1876. $vars['importid'] = $input['id'];
  1877. AjaxResponse::I()->refreshPage(array('tpl' => 'import-list-to-file', 'vars' => $vars));
  1878. return AjaxResponse::I()->toArray();
  1879. }
  1880. public function addBackupImportZonesJSON($input, $vars = array())
  1881. {
  1882. if(!$this->canAddBackup())
  1883. {
  1884. AjaxResponse::I()->addError('backups_limit_reached');
  1885. return AjaxResponse::I()->toArray();
  1886. }
  1887. $fileName = custom\helpers\ImportExportFileHelper::generateClientFileName($_SESSION['uid']);
  1888. $task = custom\TaskManager::addTask('ImportToFileWHMCS:main', array('from' => 'WHMCS', 'toFile' => $fileName, 'createdBy' => 'client'), 0, $_SESSION['uid']);
  1889. custom\TaskManager::getTaskObjectByID($task->id)->run(true);
  1890. AjaxResponse::I()->refreshPage($this->backupsHTML($input, $vars));
  1891. AjaxResponse::I()->addInfo('new_task_added');
  1892. $input['id'] = $task->id;
  1893. return $this->showListImportToFileJSON($input);
  1894. }
  1895. public function addBackupFileJSON($input, $vars = array())
  1896. {
  1897. return AjaxResponse::I()->modal('add-backupFile', $vars)->toArray();
  1898. }
  1899. public function addExportShowZonesJSON($input, $vars = array())
  1900. {
  1901. return AjaxResponse::I()->modal('add-backupFile', $vars)->toArray();
  1902. }
  1903. public function setRecordsSaveJSON($input, $vars = array())
  1904. {
  1905. $zones = $input['zone']['checked'];
  1906. $wipe = $input['wipe'];
  1907. if(!$input['setRecord'])
  1908. {
  1909. $input['setRecord'] = $this->getDefaultSet();
  1910. if(!$input['setRecord'])
  1911. {
  1912. return AjaxResponse::I()->addError('no_default_set_defined')->toArray();
  1913. }
  1914. }
  1915. if($wipe == 'on')
  1916. {
  1917. $wipe = true;
  1918. }
  1919. else
  1920. {
  1921. $wipe = false;
  1922. }
  1923. $tasks = main\models\custom\task\Repository::factory()->setFilter('name', 'DnsRecord:main')->setFilter('status', 'start')->get();
  1924. foreach($tasks as $task)
  1925. {
  1926. foreach($task->params['zones'] as $id => $zone)
  1927. {
  1928. if(array_key_exists($id, $zones) && $zones[$id] == 'on' && $zone == 'on')
  1929. {
  1930. return AjaxResponse::I()->addError('zone_already_in_task')->toArray();
  1931. }
  1932. }
  1933. }
  1934. foreach($zones as $id => $v)
  1935. {
  1936. if(!$v)
  1937. {
  1938. continue;
  1939. }
  1940. $zone = new Zone($id);
  1941. $packageId = $zone->getPackage()->id;
  1942. if($wipe == false)
  1943. {
  1944. $currentRecords = $zone->getModule()->getRecords();
  1945. $limitCheck = custom\helpers\RecordSetHelper::checkAllowedRecordsLimits($packageId, $input['setRecord'],$currentRecords);
  1946. }
  1947. elseif($wipe == true)
  1948. {
  1949. $limitCheck = custom\helpers\RecordSetHelper::checkAllowedRecordsLimits($packageId, $input['setRecord']);
  1950. }
  1951. if(!$limitCheck)
  1952. {
  1953. return AjaxResponse::I()->addError('you_have_exceeded_limit')->toArray();
  1954. }
  1955. }
  1956. $mainTask = custom\TaskManager::addTask('DnsRecord:main',array('recordId' => $input['setRecord'] , 'zones' => $zones, 'wipe' => $wipe));
  1957. AjaxResponse::I()->addInfo('set_added_successfully');
  1958. return AjaxResponse::I()->refreshPage($this->indexHTML($input))->toArray();
  1959. }
  1960. public function parseNewImportTaskList($list, &$vars)
  1961. {
  1962. foreach($list as $import)
  1963. {
  1964. $type = explode(':', $import->obj()->name);
  1965. if($type[0] == 'ImportToFileWHMCS') //Panie rilis //TODO na langa to
  1966. {
  1967. $desc = str_replace('Import', 'Backup', $import->description());
  1968. $desc = $this->praseTaskDescription($desc);
  1969. }
  1970. else
  1971. {
  1972. $desc = str_replace('Export', 'Restore', $import->description());
  1973. $desc = $this->praseTaskExportDescription($desc);
  1974. }
  1975. $desc = str_replace('WHMCS', lang::T('backup', 'system'), $desc); // TODO przerobić to na next bo mess
  1976. $vars[] = array(
  1977. 'id' => $import->obj()->id,
  1978. 'desc' => $import->description(),
  1979. 'parsedDesc' => $desc,
  1980. 'zones_imported' => '-',
  1981. 'zones_total' => '-',
  1982. 'progress' => -1,
  1983. 'type' => $import->getTaskTypeCode()
  1984. );
  1985. }
  1986. }
  1987. private function praseTaskDescription($desc)
  1988. {
  1989. $parts = explode(' from: ', $desc);
  1990. $parts[0] .= ' from: ';
  1991. $tmpParts = explode(' to: ', $parts[1]);
  1992. if(count($tmpParts) > 1)
  1993. {
  1994. $parts[1] = $tmpParts[0];
  1995. $parts[2] = ' to: ';
  1996. $parts[3] = ClientFilesManage::getFileNameWithoutClientId($tmpParts[1]);
  1997. }
  1998. return $parts;
  1999. }
  2000. private function praseTaskExportDescription($desc)
  2001. {
  2002. $parts = explode(' from: ', $desc);
  2003. $parts[0] .= ' from: ';
  2004. $tmpParts = explode(' to: ', $parts[1]);
  2005. if(count($tmpParts) > 1)
  2006. {
  2007. $parts[1] = ClientFilesManage::getFileNameWithoutClientId($tmpParts[0]);
  2008. $parts[2] = ' to: ';
  2009. $parts[3] = $tmpParts[1];
  2010. }
  2011. return $parts;
  2012. }
  2013. private function getTaskError($task) {
  2014. $erorr = false;
  2015. if($task->getStatus() == task\TaskStatusEnum::ERROR) {
  2016. $erorr = 'Error';
  2017. $results = $task->getResults();
  2018. $result = end($results);
  2019. if(isset($result->data['error'])) {
  2020. $erorr .= ' (' . $result->data['error'] . ')';
  2021. }
  2022. }
  2023. return $erorr;
  2024. }
  2025. public function parseInProgresImportTaskList($list, &$vars, $type = 'Import', $clientId = false)
  2026. {
  2027. foreach($list as $import)
  2028. {
  2029. $rep = new task\Repository();
  2030. $childTaskType = strpos($type, 'Export') === 0 ? 'export' : 'import';
  2031. $rep->byParentID($import->obj()->id)->byName($type.':'.$childTaskType);
  2032. $zones_total = $rep->count();
  2033. $rep->byStatus(task\TaskStatusEnum::FINISHED);
  2034. $zones_imported = $rep->count();
  2035. if(is_array($type))
  2036. {
  2037. $type = $type[0];
  2038. }
  2039. $task = custom\TaskManager::getXTasksObjects(1, $type.':fetchZonesList', $import->obj()->id, false, $clientId);
  2040. $error = $this->getTaskError(end($task));
  2041. $type = explode(':', $import->obj()->name);
  2042. if($type[0] == 'ImportToFileWHMCS') //Panie rilis //TODO na langa to
  2043. {
  2044. $desc = str_replace('Import', 'Backup', $import->description());
  2045. $desc = $this->praseTaskDescription($desc);
  2046. }
  2047. else
  2048. {
  2049. $desc = str_replace('Export', 'Restore', $import->description());
  2050. $desc = $this->praseTaskExportDescription($desc);
  2051. }
  2052. $desc = str_replace('WHMCS', lang::T('backup', 'system'), $desc); // TODO przerobić to na next bo mess
  2053. $vars[] = array(
  2054. 'id' => $import->obj()->id,
  2055. 'desc' => $import->description(),
  2056. 'zones_imported' => $zones_imported,
  2057. 'zones_total' => $zones_total,
  2058. 'progress' => $zones_total == 0 ? 0 : ceil($zones_imported * 100 / $zones_total),
  2059. 'error' => $error,
  2060. 'parsedDesc' => $desc,
  2061. 'type' => $import->getTaskTypeCode(),//strpos($import->description(), 'Import') === 0 ? 'Import' : 'Export'
  2062. 'status' => $import->obj()->status
  2063. );
  2064. }
  2065. }
  2066. private function redirectIfIsOnlyRDNSforCA()
  2067. {
  2068. if(GlobalSettingHelper::getSetting(GlobalSettingEnum::RDNS_IN_CLIENTAREA) == GlobalSettingEnum::CLIENTAREA_RNDS_ONLY)
  2069. {
  2070. header('Location: index.php?m=DNSManager2&mg-action=manageRDNS');
  2071. die;
  2072. }
  2073. }
  2074. /**
  2075. * @param Zone $zone
  2076. *
  2077. * @return bool
  2078. */
  2079. private function isTransferAndShouldBeAbleToEdit( Zone $zone )
  2080. {
  2081. return $this->checkWhmcsProductStatus($zone->type, $zone->relid) === 'pending transfer';
  2082. }
  2083. }