CHips L MINI SHELL

CHips L pro

Current Path : /proc/2/root/usr/local/rvglobalsoft/rvsitebuilder7/modules/rvsitebuilder7/classes/
Upload File :
Current File : //proc/2/root/usr/local/rvglobalsoft/rvsitebuilder7/modules/rvsitebuilder7/classes/Libs.pm

#!/usr/bin/perl

package RVsitebuilder7Libs;

BEGIN {
	my (@INC_OLD) = reverse @INC;
}

use strict;
use warnings;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use RVL::oAuth;
use base qw(RVL::RVGlobalSoft);
use Class::Std::Utils;

use Cpanel::Security::Authn::TwoFactorAuth           ();
use Cpanel::Security::Authn::TwoFactorAuth::Google   ();
use Cpanel::Config::userdata::TwoFactorAuth::Secrets ();
use Cpanel::Config::userdata::TwoFactorAuth::Issuers ();
use Cpanel::Exception                                ();


{

	sub new {
		my ($class) = @_;
		my ($this)  = $class->SUPER::new();
		return $this;
	}

=help
 Returns a singleton Registry instance.
=cut

	sub singleton {
		my ($class) = __PACKAGE__;

		if (!-d RVL::CpHandle::singleton()->getHomeDir() . '/.rvglobalsoft') {
			RVL::File::mkdirp(RVL::CpHandle::singleton()->getHomeDir() . '/.rvglobalsoft', '0755');
		}

		if (!defined $RVL::INSTANCE{$class}) {
			$RVL::INSTANCE{$class} = $class->new();
		}
		return $RVL::INSTANCE{$class};
	}
}

package RVsitebuidler7Libs::API;

use strict;
use warnings;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Class::Std::Utils;
use DBI;
use IO::Socket;
use Data::Dumper qw(Dumper);
#use Net::SSH::Perl;
use MIME::Base64;
use RVL::File;
use Socket;

{

	sub new {
		my ($class, $opt) = @_;
        my %hash;
        my ($this) = bless( \%hash, $class);
        return $this;
	}
	
	sub FunctionTemplate {
		my ($this , $var1, $var2) = @_; 
        RVL::logMessage('', __CONSTANT__::RVL_LOG_DEBUG);
        my $datareturn = '';
        return $datareturn;
	}



	sub covertToJSON {
		my ($this , $data)         = @_ ;
		my $dataRespJson = Dumper($data);
		$dataRespJson =~ s/(^\$)//gi;
		$dataRespJson =~ s/(\=\>)/:/gi;
		
		return $dataRespJson;
	}

	sub covertJSONToHASH {
		my ($this , $data) = @_ ;
		my $dataRespJson = {};
		my @list1        = split /,/, $data;
		foreach my $item (@list1) {
			my ($i, $j) = split(/:/, $item);
			$i =~ s/"//ig;
			$i =~ s/{//ig;
			$i =~ s/}//ig;
			$j =~ s/"//ig;
			$j =~ s/{//ig;
			$j =~ s/}//ig;
			$j =~ s/true/1/ig;
			$j =~ s/false/0/ig;
			$dataRespJson->{$i} = $j;
		}
		return $dataRespJson;
	}
	
	



	sub getUserLogin {
		my ($this) = @_ ;
		return $ENV{REMOTE_USER};
	}
	
	sub parseFile {
		my ($this , $file) = @_ ;
		my $ref_isReadSuccess = $_[1];    #if '$_[1]' not defined '$ref_isWriteSuccess' will not defined also
		my @aLines = ();
		if (open(my $FILERead, '<', $file)) {
			@aLines = <$FILERead>;
			close($FILERead);
			for (my $i = 0; $i < @aLines; $i++) {
				$aLines[$i] =~ s/\r|\n//g;
			}
			if (defined($ref_isReadSuccess) && ref($ref_isReadSuccess) eq 'SCALAR') {
				${$ref_isReadSuccess} = 1;
			}
		}
		for (my $i = 0; $i < @aLines; $i++) {
			$aLines[$i] =~ s/\r|\n//g;
		}
		return @aLines;
	}

	sub parseIniFile {
		my ($this , $file) = @_ ;
		
		my $ref_isReadSuccess =
		  $_[1];    #if '$_[1]' not defined '$ref_isReadSuccess' will not defined also
		my $res = {};

		#if (-e $file && -r $file) {
		if (open(my $FILERead, '<', $file)) {
			my $openGroup = '';
			while (<$FILERead>) {
				$_ =~ s/\r|\n//gi;
				next if (/^$/gi);
				next if (/^#/);

				#found group
				if (/^\[(.*?)\]$/) {
					$openGroup = $1;
					$openGroup =~ s/^ +//gi;
					$openGroup =~ s/ +$//gi;
					$res->{$openGroup} = {};
					next;
				}

				#normal ini
				my ($key, $value) = split(/=/, $_, 2);
				$key   = $this->trim($key);
				$value = $this->trim($value);

				if ($openGroup) {
					if (!exists $res->{$openGroup}->{$key}) {
						$res->{$openGroup}->{$key} = $value;
					}
				} else {
					$res->{$key} = $value;
				}

			}
			close($FILERead);
			if (defined($ref_isReadSuccess) && ref($ref_isReadSuccess) eq 'SCALAR') {
				${$ref_isReadSuccess} = 1;
			}
		} else {
			$res = {};
		}
		return $res;
	}

	sub parseTextFile {
		my ($this , $file) = @_ ;
		my @aLines = ();
		if (open(my $R, '<', $file)) {
			@aLines = <$R>;
			close($R);
		}
		
		return @aLines;
	}

	sub file {
		RVL::logMessage('', __CONSTANT__::RVL_LOG_DEBUG);
		my ($this , $path) = @_ ;

		my @aLines = ();
		if (-f $path) {
			if (open(my $FILERead, '<', $path)) {
				@aLines = <$FILERead>;

				#@aLines = map($_=~s/\r|\n//g, <R>);
				close($FILERead);
			}
		}

		for (my $i = 0; $i < @aLines; $i++) {
			$aLines[$i] =~ s/\r|\n//g;
		}
		return @aLines;
	}

	sub trim {
		my ($this , $string) = @_ ;
		$string =~ s/^\s+//;
		$string =~ s/\s+$//;
		return $string;
	}

	sub LWP_get_contents {
		my ($this , $host, $params, $type) = @_;
		if (!defined $type || $type eq '') {
			$type = 'get';
		}
		use LWP::UserAgent;

		$host = 'https://' . $host if ($host !~ m/^https/i);
		my ($obj) = LWP::UserAgent->new;
		$obj->ssl_opts( verify_hostname => 0 );
		$obj->agent('Perl - RV Get Content');
		my $response = {};
		if ($type eq 'post') {
			$response = $obj->post($host, $params);
		} else {
			$response = $obj->get($host);
		}

		my $output = '';
		if ($response->is_success) {
			$output = $response->decoded_content;
		} else {
			print STDERR "LWP_get_contents error: " . $response->status_line . "\n";
		}

		return $output;
	}

	sub writeFile {
		my ($this , $path, $linesRef) = @_;
		RVL::logMessage('', __CONSTANT__::RVL_LOG_DEBUG);
		my $iswriteFile = 0;
		if (open(my $FILEWrite, '>', $path)) {
			print $FILEWrite $linesRef;
			close($FILEWrite);
			$iswriteFile = 1;
		}
		return $iswriteFile;
	}

	sub parseIniFiles1 {
		my ($this , $path)  = @_;
		my %conf  = ();
		my @lines = $this->file($path);
		foreach my $array (@lines) {
			next if ($array =~ /^$/);
			my ($keys, $values) = split('=', $array, 2);
			$keys        = $this->trim($keys);
			$values      = $this->trim($values);
			$conf{$keys} = $values;
		}
		return %conf;
	}

	sub getAppName {
		my $appName = 'cpanel';
		if ($ENV{SERVER_PORT} eq '2086' || $ENV{SERVER_PORT} eq '2087') {
			$appName = 'whm';
		} elsif ($ENV{SERVER_PORT} eq '2095' || $ENV{SERVER_PORT} eq '2096') {
			$appName = 'webmail';
		}
		return $appName;
	}

	sub getLatestVersion {
		my ($this) = @_ ;
		my ($request) = "/latestversion.php?program=symantecvip";

		my ($host) = 'download.rvglobalsoft.com';

		my $response       = $this->LWP_get_contents($host . $request);
		my @resp           = split(/\n+/, $response);
		my $latest_version = '-';
		foreach my $line (@resp) {
			$line = $this->trim($line);
			next if ($line =~ /^$/);
			$latest_version = $line;
			my ($pname, $pversion) = split(/:/, $latest_version, 2);
			$pversion =~ s/^\s+|\s+$|\<br\>//g;
			$latest_version = $pversion;
		}

		return $latest_version;
	}

	sub getCurrentVersion {
		my ($this) = @_;
		my $current_version = '0.0';
		my $versionFile     = '/usr/local/rvglobalsoft/rvadmintools/rvadmintoolsversion.txt';
		my @version = ();
		if (-f $versionFile) {
			@version         = $this->parseFile($versionFile);
			$current_version = $version[0];
		}
		chomp($current_version);
		return $current_version;
	}



	sub extracturl {
		my ($this , $url) = @_;
		my ($host, $port, $path);
		$url =~ s/http:\/\///;
		$url =~ s/https:\/\///;
		$host = $url;
		if ($url =~ /\//) {
			($host, $path) = split(/\//, $url, 2);
			$path = '/' . $path;
			$url =~ s/\/.*//;
		}
		if ($url =~ /:/) {
			($host, $port) = split(/:/, $host, 2);
		}
		
		return ($host, $port, $path);
	}

	sub getcontentbyurl {
		my ($this , $url) = @_ ;

		my ($host, $port, $path) = $this->extracturl($url);

		my %OPT;

		if ($url =~ '^https:\/\/') {
			$OPT{'usessl'} = 1;
		}

		$OPT{'host'}    = $host;
		$OPT{'port'}    = $port;
		$OPT{'request'} = $path;
		$OPT{'method'}  = 'GET';
		my %result = $this->socket2(%OPT);
		
		return %result;
	}

	sub socket2 {
		my ($this , %OPT) = @_;

		#prepare vars
		my %result;
		my ($host, $port, $request, $args, $method, $usessl);

		$host    = defined $OPT{'host'}    ? $OPT{'host'}    : '';
		$port    = defined $OPT{'port'}    ? $OPT{'port'}    : '';
		$request = defined $OPT{'request'} ? $OPT{'request'} : '/';
		$args    = defined $OPT{'args'}    ? $OPT{'args'}    : '';
		$method  = defined $OPT{'method'}  ? $OPT{'method'}  : 'GET';
		$usessl  = defined $OPT{'usessl'}  ? $OPT{'usessl'}  : 0;

		my ($authBasic, $user, $password, $accountEncode);

		$authBasic = defined $OPT{'authbasic'} ? $OPT{'authbasic'} : '0';
		$user      = defined $OPT{'user'}      ? $OPT{'user'}      : '';
		$password  = defined $OPT{'password'}  ? $OPT{'password'}  : '';

		$accountEncode = '';

		if ($authBasic) {
			$password =~ s/[\r\n]+//g;
			$accountEncode = "$user:$password";
			$accountEncode = encode_base64_2("$user:$password");
		}

		if ($usessl) {
			$this->_printdebug("## SSL Connect ##");
			
			#print STDERR "## SSL Connect ## \n";
			
			%result = $this->_sslsocket($host, $port, $request, $args, $method, $accountEncode);
		} else {
			
			$this->_printdebug("## None SSL Connect ##");
			#print STDERR "## None SSL Connect ## \n";
			%result =
			  $this->_nonsslsocket($host, $port, $request, $args, $method, $authBasic, $accountEncode);
		}
		return %result;
	}

	sub _nonsslsocket {
		my ($this , $host, $port, $request, $args, $method, $authBasic, $accountEncode) = @_;

		$port = ($port ne '') ? $port : '80';

		my %result;
		my ($sin, $ipaddr, $len, $header);

		socket(SOCKET, PF_INET, SOCK_STREAM, 0);

		$ipaddr = gethostbyname($host);
		if (!defined($ipaddr)) {
			$result{'socketfail'} = "Cannot get protocal by hostname $host";
			return %result;
		}

		$sin = sockaddr_in($port, $ipaddr);
		if (!connect(SOCKET, $sin)) {
			$result{'socketfail'} = "Cannot create socket connection to server `$host`";
			return %result;
		}

		if ($method eq 'GET') {
			if ($args ne '') {
				$request .= "?$args";
			}
			$args = '';
		}

		my $oldfh = select(SOCKET);
		$| = 1;
		select($oldfh);
		my ($referer) = "http://$host$request";

		$len    = length($args);
		$header = "$method $request HTTP/1.1\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Host: $host\r\n";
		$header .= "Content-Length: $len\r\n";
		$header .= "Connection: Keep-Alive\r\n";
		$header .= "Cache-Control: no-cache\r\n";
		$header .= "Referer: $referer\r\n";
		$header .= "\r\n";

		if ($authBasic) {
			$header .= "Authorization: Basic " . $accountEncode . "\r\n";
		}

		$header .= $args;

		print SOCKET $header;

		my ($inheaders) = 1;

		while (<SOCKET>) {
			if ($_ =~ /^\r\n$/) {
				$inheaders = 0;
			}
			my $temp = $_;
			chomp($temp);

			if ($inheaders) {
				$temp =~ s/\n//g;
				$temp =~ s/\s$//g;

				my ($key, $value) = split(/: /, $temp);
				chomp($key);
				chomp($value);
				if ($key =~ /^http\//i) {
					$result{'header'}{'httpresponse'} = $temp;
				}
				$result{'header'}{ lc($key) } = $value;
			} else {
				$result{'page'} .= $temp;
			}
		}

		close SOCKET;
		return %result;
	}

	sub _sslsocket {
		my ($this , $host, $port, $request, $args, $method, $accountEncode) = @_;

		my %result;
		my $socketResult = '';
		my $page         = '';
		my $httpresponse = '';
		my %headers;

		$port = ($port ne '') ? $port : '443';

		my $hasNetSSLeay = `perl -e 'eval { require Net::SSLeay; print 1; }' 2>&1`;

		if ($hasNetSSLeay eq '0') {
			$result{'socketfail'} = 'Not support Net::SSLeay';
			return %result;
		}

		if ($method && $method eq 'POST') {
			$socketResult = `perl -e "
	        use Net::SSLeay;
	        print join\('{RVNL}',Net::SSLeay::post_https\( '$host', '$port', '$request',Net::SSLeay::make_headers\( 'Authorization' => 'Basic $accountEncode', 'Connection' => 'close' \),'$args'\)\);
	        " 2>&1`;
		} else {
			if ($args ne '') {
				$request .= "?$args";
			}
			$socketResult = `perl -e "
	        use Net::SSLeay;
	        print join\('{RVNL}',Net::SSLeay::get_https\( '$host', '$port', '$request',Net::SSLeay::make_headers\( 'Authorization' => 'Basic $accountEncode', 'Connection' => 'close' \)\)\);
	        " 2>&1`;
		}

		($page, $httpresponse, %headers) = split('{RVNL}', $socketResult);

		$result{'header'}{'httpresponse'} = $httpresponse;
		foreach my $headkey (keys %headers) {
			$result{'header'}{ lc($headkey) } = $headers{$headkey};
		}
		$result{'page'} = $page;
		return %result;
	}

	sub encode_base64_2 {
		my $res = "";
		my $eol = "\n";
		pos($_[0]) = 0;
		while ($_[0] =~ /(.{1,45})/gs) {
			$res .= substr(pack("u", $1), 1);
			chop($res);
		}
		$res =~ tr/` -_/AA-Za-z0-9+\//;
		my $padding = (3 - length($_[0]) % 3) % 3;
		$res =~ s/.{$padding}$/"=" x $padding/e if $padding;
		if (length $eol) {
			$res =~ s/(.{1,76})/$1$eol/g;
		}
		return $res;
	}

	sub _printdebug {
		my ($this , $msg) = @_ ;
		my $DEBUG;
		print ":: LOG :: $msg\n" if $DEBUG;
	}

	sub getcookie {
		my ($this , $cookie_key) = @_ ;
		return '' if !defined($cookie_key);
	}


	sub getHostName {
		my ($this , $cmd)      =  @_ ; 
		my $hostName = RVL::CpHandle::singleton()->getHostname();
		return $hostName;
	}
	

	
	sub parseNSFile {
		my ($this , $path)  = @_;
		my %conf  = ();
		my @lines = $this->file($path);
		foreach my $array (@lines) {
			next if ($array =~ /^$/);
			my ($keys, $values) = split(':', $array, 2);
			$keys        = $this->trim($keys);
			$values      = $this->trim($values);
			$conf{$keys} = $values;
		}
		return %conf;
	}
	

	sub getRVadmintoolsLatestVersion{
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
    	my ($this) = @_;
    	my $program = 'rvadmintools';
        my($request) = "/latestversion.php?program=$program&getarray=perl";
	    my($host) = 'download.rvglobalsoft.com';
	    
	    my $response = $this->LWP_get_contents($host.$request);
	    my @resp = split(/\n+/, $response);
	    my $latest_version = '1.0.0';
	    foreach my $line (@resp) {
	        $line = $this->trim($line);
	        next if ($line =~ /^$/);
	        
	        $latest_version = $line;
	        if ($program eq 'rvsitebuilder') {
	            $latest_version =~ s/\n|\s//g;
	        } else {
	            my ($pname, $pversion) = split(/=/, $latest_version,2);
	            $pversion =~ s/^\s+|\s+$//;
	            $latest_version = $pversion;
	        }
	    }
	    #updateVersionCache($program, $latest_version);
	    return $latest_version;
    }




	sub getFullURL {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
		my ($this) = @_;
		my $fullurl = '';
		my $protocol = 'http://';
		if ($ENV{'SERVER_PORT'} eq '2087') {
			$protocol = 'https://';
		}
		my $servername = $this->getHostName();
		$fullurl = $protocol.$servername.':'.$ENV{'SERVER_PORT'}.$ENV{cp_security_token};
		return $fullurl;
	}
	
	sub getRvadminPath {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;
        my $userlogin = $this->getUserLogin();
        my $rvadminhomepath = (getpwnam('rvadmin'))[7];
        if ($userlogin ne 'root') {
        	$rvadminhomepath = (getpwnam($userlogin))[7];
        	$rvadminhomepath = $rvadminhomepath.'/rvadmin';
        }
        return $rvadminhomepath;        
	}
	
	sub getEmailTweak {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;
        my $rvadminpath = $this->getRvadminPath();             
        my $tempconfig = RVL::File::parse_ini_file($rvadminpath.'/_global');
        my $emailconfig = {};
        $emailconfig->{'readwebmail_skipicon'} = (defined $tempconfig->{'readwebmail_skipicon'} && $tempconfig->{'readwebmail_skipicon'} eq '1') ? $tempconfig->{'readwebmail_skipicon'} : '0';
        $emailconfig->{'editemailquota_skipicon'} = (defined $tempconfig->{'editemailquota_skipicon'} && $tempconfig->{'editemailquota_skipicon'} eq '1') ? $tempconfig->{'editemailquota_skipicon'} : '0';
        $emailconfig->{'changeemailpassword_skipicon'} = (defined $tempconfig->{'changeemailpassword_skipicon'} && $tempconfig->{'changeemailpassword_skipicon'} eq '1') ? $tempconfig->{'changeemailpassword_skipicon'} : '0';
        $emailconfig->{'aging_skipicon'} = (defined $tempconfig->{'aging_skipicon'} && $tempconfig->{'aging_skipicon'} eq '1') ? $tempconfig->{'aging_skipicon'} : '0';
        $emailconfig->{'outlook_skipicon'} = (defined $tempconfig->{'outlook_skipicon'} && $tempconfig->{'outlook_skipicon'} eq '1') ? $tempconfig->{'outlook_skipicon'} : '0';
        $emailconfig->{'resell_inheritemail'} = (defined $tempconfig->{'resell_inheritemail'} && $tempconfig->{'resell_inheritemail'} eq '1') ? $tempconfig->{'resell_inheritemail'} : '0';      
        
	    return $emailconfig;
	}
	
	sub saveEmailAllowList {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
		my ($this ,$key, $valset) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my $tempconfig = RVL::File::parse_ini_file($rvadminpath.'/_global');
        $tempconfig->{$key} = $valset;
        my $resp->{complete} = RVL::File::write_ini_file($rvadminpath.'/_global', $tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/_global');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/_global');
        return $resp;       
	}
	
	sub getDisableFullBackup {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;
        my $rvadminpath = $this->getRvadminPath();             
        my $tempconfig = RVL::File::parse_ini_file($rvadminpath.'/_global');
        my $backupconfig = {};
        $backupconfig->{'skip_gen_full_backup'} = (defined $tempconfig->{'skip_gen_full_backup'} && $tempconfig->{'skip_gen_full_backup'} eq '1') ? $tempconfig->{'skip_gen_full_backup'} : '0';
        
        return $backupconfig;
	}
	
	sub getMysqlRemote {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;
        my $rvadminpath = $this->getRvadminPath();             
        my @tempconfig = $this->parseFile($rvadminpath.'/.rvskipdbremote');
        $tempconfig[0] = ($tempconfig[0] eq '') ? '0;0' : $tempconfig[0];
        my $remotesqlconfig = {};
        ($remotesqlconfig->{'remotesqlconf'},$remotesqlconfig->{'remotesqlconf_resell'}) = split(/;/,$tempconfig[0]);
        
        return $remotesqlconfig;
       
	}
	
	sub saveMysqlAccessHost {
		RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $setting) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = $this->parseFile($rvadminpath.'/.rvskipdbremote');
        $tempconfig[0] = ($tempconfig[0] eq '') ? '0;0' : $tempconfig[0];
        #for root , root have 2 config val 1;1
        if ($tempconfig[0] =~ m/\;/) {
        	$tempconfig[0] =~ s/^(.)/$setting/g;
        }
        #for reseller
        else{
        	$tempconfig[0] = $setting;
        }
        my $resp->{complete} = $this->writeFile($rvadminpath.'/.rvskipdbremote',@tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/.rvskipdbremote');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/.rvskipdbremote');
        return $resp; 
            
	}
	
	sub saveMysqlAccessHost_resell {
        RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $setting) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = $this->parseFile($rvadminpath.'/.rvskipdbremote');
        $tempconfig[0] = ($tempconfig[0] eq '') ? '0;0' : $tempconfig[0];
        $tempconfig[0] =~ s/(.)$/$setting/g;
        my $resp->{complete} = $this->writeFile($rvadminpath.'/.rvskipdbremote',@tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/.rvskipdbremote');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/.rvskipdbremote');
        return $resp; 
             
    }
    sub getDisableSpambox {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = $this->parseFile($rvadminpath.'/.rvskipspambox');
        my @tempconfig2 = $this->parseFile($rvadminpath.'/.skipspambox2allresell');
        my $skipspambox = {};
        $skipspambox->{skip_spam_box} = (defined $tempconfig[0] && $tempconfig[0] ne '') ? $tempconfig[0] : '0';
        $skipspambox->{resell_skip_spambox} = (defined $tempconfig2[0] && $tempconfig2[0] ne '') ? $tempconfig2[0] : '0';
        return $skipspambox;    
    }
    
    sub saveSpamBox {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $setting) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = ($setting);       
        my $resp->{complete} = $this->writeFile($rvadminpath.'/.rvskipspambox',@tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/.rvskipspambox');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/.rvskipspambox');
        return $resp; 
    }
    
    sub saveSpamBox_resell {
        RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $setting) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = ($setting);       
        my $resp->{complete} = $this->writeFile($rvadminpath.'/.skipspambox2allresell',@tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/.skipspambox2allresell');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/.skipspambox2allresell');
        return $resp; 
    }
    
    sub getEmailForward {
        RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = $this->parseFile($rvadminpath.'/_rvaolblacklist');
        if ($tempconfig[0] eq '') {
        	$tempconfig[0] = "# A domain from this list is specified\n". 
        	                 "# by the user as the target recipient of a forwarder,\n".
					         "# then the user will NOT be allowed to create the forwarder\n".
					         "# Format: domain name listed line by line\n".
					         "# Examples:\n". 
					         "# example.com\n";
        }
        my $aolconfig = {};
        foreach (@tempconfig) {
        	chomp($_);
            $aolconfig->{aolconfig} = $aolconfig->{aolconfig}.$_."\n";
        } 
        return $aolconfig;
    }
    
    sub saveAOLData {
        RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this,$data) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my @tempconfig = ($data);
        my $resp->{complete} = $this->writeFile($rvadminpath.'/_rvaolblacklist',@tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/_rvaolblacklist');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/_rvaolblacklist');
        return $resp; 
    }
    
    sub saveCronLimit {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $valset) = @_;
        my $rvadminpath = $this->getRvadminPath();                     
        my $tempconfig = RVL::File::parse_ini_file($rvadminpath.'/_global');
        $tempconfig->{'cronlimit'} = $valset;
        my $resp->{complete} = RVL::File::write_ini_file($rvadminpath.'/_global', $tempconfig);
        $resp->{chownercomplete} = $this->chOwnerRvadmin($rvadminpath.'/_global');
        $resp->{chmodcomplete} = $this->ChMod($rvadminpath.'/_global');
        return $resp;    	
    }
    
    sub getCronLimit {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;
        my $rvadminpath = $this->getRvadminPath();             
        my $tempconfig = RVL::File::parse_ini_file($rvadminpath.'/_global');
        my $conlimit = {};
        $conlimit->{'cronlimit'} = (defined $tempconfig->{'cronlimit'} && $tempconfig->{'cronlimit'} ne '') ? $tempconfig->{'cronlimit'} : '0';
        
        return $conlimit;
    }
    
    sub getErrorLog {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;        
        open R,'tail -n 30 /usr/local/cpanel/logs/error_log|';
        my (@tempconfig)=<R>;    
        my $errorlog = {};        
        foreach (@tempconfig) {
            chomp($_);
            $errorlog->{errorlog} = $errorlog->{errorlog}.$_."\n";
        } 
        return $errorlog;    	
    }
    
    sub getCpanelErrorLog {
        RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);     
        my ($this) = @_;        
        open R, 'tail -n 30 /usr/local/cpanel/logs/error_log|' or die "Could not open file $!";
        my (@tempconfig)=<R>;
        close(R);
          
        my $resp = {};
        $resp->{logdata} = '';        
        foreach (@tempconfig) {
            chomp($_);
            $resp->{logdata} = $resp->{logdata}.$_."\n";
        }
        $resp->{complete} = 1;
        if(!defined($resp->{logdata}) || $resp->{logdata} eq ''){
        	$resp->{complete} = 0;
        } 
        return $resp;              
    }
    
    sub chOwnerRvadmin {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $fileconfig) = @_;
        my $success = system('chown','rvadmin:rvadmin',$fileconfig);
        return $success;
    }
    
    sub ChMod {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
        my ($this, $fileconfig) = @_;
        my $success = system('chmod','755',$fileconfig);
        return $success;
    }
    
    sub GATracking {
    	RVL::logMessage('' , __CONSTANT__::RVL_LOG_DEBUG);
    	my ($this,$viewtype,$apptype) = @_;
    	my $resp = {};
    	
    	eval{
    		my $rvadmintoolsversion = $this->getCurrentVersion();
    		use RVL::Rvanalytics;
        
	        my ($OAnalytics) = RVL::Rvanalytics->new(
	            'tid' => 'UA-65722035-6',
	            'cid' => md5($this->getHostName().'_'.$this->getUserLogin()),
	            'uid' => md5($this->getHostName().'_'.$this->getUserLogin()),
	            'aid' => 'RVAdmintools',
	            'an' => 'RVAdmintools',
	            'ds' => 'RVAdmintools',
	            'av' => $rvadmintoolsversion,
	        );
	   		if ($viewtype eq 'screenview') {
	          
	            $OAnalytics->send('screenview', {
	                'av'    => "$rvadmintoolsversion",
	                'aid'   => 'RVAdmintools',
	                'cd'    => "$apptype",
	            });
	            
	            $OAnalytics->send('event', {
	                'ec' => 'RVAdmintools/PageType', 
	                'ea' => "$apptype", 
	            });
	            
	            if ($apptype eq 'rvadmintoolsmanager') {
	                if ($this->getUserLogin() eq "root") {
	                    # Root
	                    my (%osConf) = %{$this->lsOSVersion()};
	                    if (defined $osConf{'id'} && $osConf{'id'} ne '') {
	                        $OAnalytics->send('event', {
	                            'ec' => 'RVAdmintools/ServerOSVersion', 
	                            'ea' => $osConf{'id'}, 
	                            'el' => $osConf{'release'}
	                        });
	                    }
	                    $OAnalytics->send('event', {
	                        'ec' => 'RVAdmintools/AccressManagerBy', 
	                        'ea' => 'root', 
	                    });
	                    
	                    my ($serverType) = $this->isVPSServer() eq 0 ? 'Dedicated': 'VPS';
	                        $OAnalytics->send('event', {
	                        'ec' => 'RVAdmintools/ServerType', 
	                        'ea' => $serverType, 
	                    });
	                    
	                    my ($isCloundLinux) = $this->isCloudlinux();
	                    if ($isCloundLinux) {
	                        my ($cloundLinuxConf) = $this->lsCloundLinuxConf();
	                        if ($cloundLinuxConf) {
	                            my (@confList) = ('cpu', 'ncpu', 'io', 'vmem', 'pmem', 'nproc', 'other' , 'mem', 'iops');
	                            # cloundLinux defaults package
	                            if (defined $cloundLinuxConf->{'defaults'}) {
	                                my (@defPackage) = @{$cloundLinuxConf->{'defaults'}};
	                                foreach my $configList (@confList) {
	                                    if (defined $defPackage[0]->{$configList}) {
	                                        foreach my $configAttr (keys %{$defPackage[0]->{$configList}}) {
	                                            $OAnalytics->send('event', {
	                                                'ec' => 'RVAdmintools/CloundLinuxConfig/'.$configList, 
	                                                'ea' => $configAttr, 
	                                                'el' => 'defaults',
	                                                'ev' => $defPackage[0]->{$configList}->{$configAttr},
	                                            });
	                                        }
	                                    }
	                                }
	                            }
	                            # cloundLinux other package 
	                            if (defined $cloundLinuxConf->{'package'}) {
	                                foreach my $cloundPackageName (keys %{$cloundLinuxConf->{'package'}}) {
	                                    foreach my $configList (@confList) {
	                                        if (defined $cloundLinuxConf->{'package'}->{$cloundPackageName}->{$configList}) {
	                                            foreach my $configAttr (keys %{$cloundLinuxConf->{'package'}->{$cloundPackageName}->{$configList}}) {
	                                                $OAnalytics->send('event', {
	                                                    'ec' => 'RVAdmintools/CloundLinuxConfig/'.$configList, 
	                                                    'ea' => $configAttr, 
	                                                    'el' => $cloundPackageName,
	                                                    'ev' => $cloundLinuxConf->{'package'}->{$cloundPackageName}->{$configList}->{$configAttr},
	                                                });
	                                            }
	                                        }
	                                    }
	                                }
	                            }
	                        }
	                    }
	                } else {
	                    # Reseller
	                    $OAnalytics->send('event', {
	                        'ec' => 'RVAdmintools/AccressManagerBy', 
	                        'ea' => 'reseller', 
	                    });    
	                }
	            } elsif ($apptype eq 'submit_cron') {
                 	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'cron setup', 
                    });
	            } elsif  ($apptype eq 'edit_email') {
	            	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'email setup', 
                    });
	            } elsif  ($apptype eq 'full_backup') {
	            	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'skip full backup', 
                    });
	            } elsif  ($apptype eq 'mysql_remote') {
	            	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'skip mysql remote', 
                    });
	            } elsif  ($apptype eq 'skip_spambox') {
	            	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'skip spambox', 
                    });
	            } elsif  ($apptype eq 'email_forwarder_setup') {
	            	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'email forwarder setup', 
                    });
	            } elsif  ($apptype eq 'error_log') {
	            	$OAnalytics->send('event', {
                        'ec' => 'RVAdmintools/FeatureUsage', 
                        'ea' => 'view cpanel error log', 
                    });
	            } else {
	            	##
	            }
	            
	        }
	        $resp->{complete} = 1;
	        $resp->{message} = "sent analytic success viewtype:".$viewtype." apptype:".$apptype;
    	};
    	
    }
    
    sub lsOSVersion{
	    my (%osConf) = (
	        'id' => '',
	        'release' => '',
	        'codename' => '',
	    );
	    
	    if (-f '/etc/redhat-release') {
	        # CentOS, redhat, CloudLinux
	        open(my $FD, '<', '/etc/redhat-release'); 
	        my ($line) = join('', <$FD>);
	        close($FD);
	        if ($line =~ /(.*?) release (\d+\.\d+\.\d+|\d+\.\d+|\d+) \((.*?)\)/gi) {
	            $osConf{'id'} = $1;
	            $osConf{'release'} = $2;
	            $osConf{'codename'} = $3;
	        }
	    } elsif (-f '/etc/SuSE-release') {
	        # SUSE Linux
	        $osConf{'id'} = 'SUSE Linux';
	        open(my $FD, '<', '/etc/SuSE-release'); 
	        my (@line) = <$FD>;
	        close($FD);
	        foreach my $inLine (@line) {
	            chomp($inLine);
	            my ($key, $val) = split(/=/, $inLine, 2);
	            chomp($key); chomp($val);
	            if (uc($key) eq 'VERSION') {
	                $osConf{'release'} = $val;
	            } 
	        }
	        
	    } elsif (-f '/etc/mandrakelinux-release') {
	        # Mandrakelinux
	        open(my $FD, '<', '/etc/mandrakelinux-release'); 
	        my ($line) = join('', <$FD>);
	        close($FD);
	        if ($line =~ /(.*?) release (\d+\.\d+\.\d+|\d+\.\d+|\d+) \((.*?)\)/gi) {
	            $osConf{'id'} = $1;
	            $osConf{'release'} = $2;
	            $osConf{'codename'} = $3;
	        }
	    } elsif (-f '/etc/mandrake-release') {
	        # Mandrakelinux
	        open(my $FD, '<', '/etc/mandrake-release'); 
	        my ($line) = join('', <$FD>);
	        close($FD);
	        if ($line =~ /(.*?) release (\d+\.\d+\.\d+|\d+\.\d+|\d+) \((.*?)\)/gi) {
	            $osConf{'id'} = $1;
	            $osConf{'release'} = $2;
	            $osConf{'codename'} = $3;
	        }
	    } elsif (-f '/etc/lsb-release') {
	        # Ubuntu
	        open(my $FD, '<', '/etc/lsb-release'); 
	        my (@line) = <$FD>;
	        close($FD);
	        foreach my $inLine (@line) {
	            chomp($inLine);
	            my ($key, $val) = split(/=/, $inLine, 2);
	            chomp($key); chomp($val);
	            if (uc($key) eq 'DISTRIB_ID') {
	                $osConf{'id'} = $val;
	            }
	            if (uc($key) eq 'DISTRIB_RELEASE') {
	                $osConf{'release'} = $val;
	            }
	            if (uc($key) eq 'DISTRIB_CODENAME') {
	                $osConf{'codename'} = $val;
	            }
	        }
	    }
	    
	    return wantarray ? ($osConf{'id'}, $osConf{'release'}, $osConf{'codename'}) : \%osConf;
	}
	
	sub isVPSServer{
	    my ($isVPS) = 0;
	    eval {
	        require Sys::Detect::Virtualization;
	        my ($detector) = Sys::Detect::Virtualization->new();
	        my (@found) = $detector->detect();
	        if (@found) {
	            $isVPS = 1;
	        }
	    };
	    return $isVPS;
	}
	
	sub isCloudlinux{
	    if (-f '/etc/sysconfig/lve') {
	        open(my $FD, '<', '/etc/sysconfig/lve'); 
	        my (@line) = <$FD>;
	        close($FD);
	        my (%lveConf);
	        foreach my $inLine(@line) {
	            chomp($inLine);
	            my ($key, $val) = split(/=/, $inLine, 2);
	            chomp($key); chomp($val);
	            $lveConf{$key} = $val
	        }
	        if (defined $lveConf{'LVE_ENABLE'} && lc($lveConf{'LVE_ENABLE'}) eq 'yes') {
	            return 1;
	        } else {
	            return 0; 
	        }
	    } else {
	        return 0;
	    }
	}
	sub lsCloundLinuxConf{
	    my ($ref);
	    eval{
	        require XML::Simple;
	        my ($xs) = XML::Simple->new();
	        $ref = $xs->XMLin('/etc/container/ve.cfg', KeyAttr => {'package' => 'id'}, ForceArray => ['defaults', 'package']);
	    };
	    return $ref;
	}
}

1;

Copyright 2K16 - 2K18 Indonesian Hacker Rulez