dashboard.php 95 KB

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