<?


####################################################################################################
### GETTING ACTIVATION CODE BY CLIENT URL
####################################################################################################
/*
* Check if a given string needs addslashes. Should be used before database operation.
**************************************************************************************/
function GetLicenseNumber($data){
        
    $postFields["project"]                   = "eDirectory";
    $postFields["version"]                   = $data["customer_version"];
    $postFields["event_feature"]             = "on";
    $postFields["banner_feature"]            = "on";
    $postFields["classified_feature"]        = "on";
    $postFields["article_feature"]           = "on";
    $postFields["listingtemplate_feature"]   = "on";
    $postFields["mobile_feature"]            = ($data["customer_feature_mobile"] == "on" ? "on" : "");
    $postFields["multilanguage_feature"]     = "on";
    $postFields["zipproximity_feature"]      = "on";
    $postFields["branded_feature"]           = ($data["customer_feature_branding"] == "on" ? "on" : "");
    $postFields["modrewrite_feature"]        = "on";
    $postFields["custominvoice_feature"]     = "on";
    $postFields["claim_feature"]             = "on";
    $postFields["paymentsystem_feature"]     = "on";
    $postFields["sitemap_feature"]           = "on";
    $postFields["client"]                    = "ArcaSolutions";
    $postFields["times"]                     = 1;

    $ch = curl_init('http://activation.arcasolutions.com/getlicense_auto.php');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_REFERER, "http://".$data["customer_url"]);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, "demoDirectoryAutomationInstall");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


    // Sending email with error
    $mail_content  = "==============================================================".PHP_EOL;
    $mail_content .= date("Y-m-d H:i:s")." - CURL Fields: ".PHP_EOL;
    foreach ($postFields as $key => $value) {
        $mail_content .= $key.": ".$value.PHP_EOL;
    }
    $mail_content .= "==============================================================".PHP_EOL;
    

    if($response = curl_exec($ch)){
        if($response){
            $mail_content .= date("Y-m-d H:i:s")." - CURL Response: ".$response.PHP_EOL;
            $mail_content .= "==============================================================".PHP_EOL;
            mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - CURL - Activating: '.date("Y-m-d H:i:s"),$mail_content);
            $licensenumber = $response;

            if(doActivationEdir($data["customer_url"],$data["customer_database_name"],$licensenumber,$postFields["version"])){
                //echo "eDirectory Activated!!";
                return true;
            }else{
                //$log_message = " Error Activating".PHP_EOL;
                //$this->GenerateLogReport($log_message,true);
                $mail_content = date("Y-m-d H:i:s")." - Error Activating private...";
                mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - CURL Error '.date("Y-m-d H:i:s"),$mail_content);
            }
        }else{

        }
    }else{ 
        $curl_error_message = curl_error($ch);
        
        // Sending email with error
        $mail_content  = "==============================================================".PHP_EOL;
        $mail_content .= date("Y-m-d H:i:s")." - PHP Line......: ".__LINE__.PHP_EOL;
        $mail_content .= date("Y-m-d H:i:s")." - CURL Error: ".$curl_error_message.PHP_EOL;
        $mail_content .= "==============================================================";
        mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - CURL Error: '.date("Y-m-d H:i:s"),$mail_content);

        echo $curl_error_message;
    }
    


}


function db_stringNeedsAddslashes($str) {
	if (($qp = strpos($str,"'")) !== false || ($qp = strpos($str,"\"")) !== false) {
	if ($str[$qp-1] != "\\")
		return true;
	else
		return db_stringNeedsAddslashes(substr($str,$qp+1,strlen($str)));
	}
	return false;
}

function db_formatString($string, $default = "", $import = false, $simpleQuotes = true) {
    if ($import){
        if (!$string){
           $string = "'".$string."'"; 
        } elseif (is_string($string)) {
            if ((strpos($string,"\'") !== false) || (strpos($string,"\\") !== false) || (strpos($string,"\\\"") !== false) || !get_magic_quotes_gpc()){
                $string = stripslashes($string);
            }
            $string  = addslashes($string);
            $string = "'".$string."'";
        } elseif (is_numeric($string)) {
            return $string;
        } else {
            $string = "'".$string."'";
        }
        return $string;
        
    } else {
        
        if (empty($string) && $string != "0") {
            $string = $default;
        }
        if (($string[0]=="'" && $string[strlen($string)-1]=="'") || ($string[0]=='"' && $string[strlen($string)-1]=='"')) {
            $string = substr($string, 1, strlen($string)-2);
        }
        if (db_stringNeedsAddslashes($string)) {
            $string = addslashes($string);
        }
        if ($simpleQuotes){
            return "'".$string."'";
        } else {
            return $string;
        }
    }
	
}

function softwareRegistration($licensenumber, $domain, $version, $activationcode,$db_name) {

	$activationcodecheck = getActivationCode($licensenumber, $domain, $version);
	if (($activationcodecheck) && ($activationcodecheck == $activationcode)) {

		$filename = $_SERVER["DOCUMENT_ROOT"]."/custom/reg.key";
		$filenameContent = strtoupper($licensenumber)."|".$domain."|".$version."|".strtoupper($activationcode)."\n";
		if (is_writable($filename)) {
			if (!$handle = fopen($filename, "a")) {
				return false;
			}
			if (fwrite($handle, $filenameContent) === false) {
				return false;
			}
			fclose($handle);
		} else {
			return false;
		}

		//$dbObj = db_getDBObject(DEFAULT_DB,true);

		$dbObj = new mysqli(_DIRECTORYDB_HOST, _DIRECTORYDB_USER, _DIRECTORYDB_PASS, $db_name);

		$domainsql = db_formatString(strtolower($domain));
		$date_time = db_formatString(date("Y-m-d H:i:s"));

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('a', $domainsql, $date_time, ".db_formatString(strtoupper($licensenumber)).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('b', $domainsql, $date_time, ".db_formatString(strtoupper($activationcode)).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('c', $domainsql, $date_time, ".db_formatString(strtoupper(md5($licensenumber.$activationcode))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('d', $domainsql, $date_time, ".db_formatString(strtoupper(md5($licensenumber.$domain))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('e', $domainsql, $date_time, ".db_formatString(strtoupper(md5($licensenumber.$version))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('f', $domainsql, $date_time, ".db_formatString(strtoupper(md5($licensenumber.$activationcode.$domain.$version))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('g', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode.BRANDED_PRINT))).")";
		$dbObj->query($sql);
		
		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('h', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."EVENT_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('i', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."BANNER_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('j', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."CLASSIFIED_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('k', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."ARTICLE_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('l', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."ZIPCODE_PROXIMITYoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('m', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."MODREWRITE_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('n', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."CUSTOM_INVOICE_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('o', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."CLAIM_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('p', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."LISTINGTEMPLATE_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('q', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."MOBILE_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('r', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."MULTILANGUAGE_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('s', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."PAYMENTSYSTEM_FEATUREoff"))).")";
		$dbObj->query($sql);

		$sql = "INSERT INTO Registration (name, domain, date_time, value) VALUES ('t', $domainsql, $date_time, ".db_formatString(strtoupper(md5($activationcode."SITEMAP_FEATUREoff"))).")";
		$dbObj->query($sql);

		$dbObj->close();

		return true;

	}

	return false;

}


function getActivationCode($licensenumber, $domain, $version) {
	$activationcode == "";
	//$activationcode = exec($_SERVER["DOCUMENT_ROOT"]."/bin/linux32bits/reg.bin registration ".$licensenumber." ".$domain." ".$version." null getactivationcode", $execreturn);
				
	$activationcode = $licensenumber.$domain.$version;
	for ($i=0; $i<strlen($activationcode); $i++) {
		if (!($i%10)) {
			$activationcode[$i] = '.';
		}
		$auxInt = ord($activationcode[$i]);
		$auxInt += 2;
		$auxInt %= 255;
		$activationcode[$i] = chr($auxInt);
	}

	$activationcodemd5 = md5($activationcode);
	$activationcode = strtoupper($activationcodemd5);

	return $activationcode;

}


function doActivationEdir($domain,$db_name,$licensenumber,$version){

	$ch = curl_init();
	if ($ch) {

		$curl_setopt_count_error = 0;
		$autoregistrationdomain = "http://activation.arcasolutions.com";
		curl_setopt($ch, CURLOPT_URL, $autoregistrationdomain."/auto_registration.php");
		curl_setopt($ch, CURLOPT_USERAGENT, "demoDirectoryAutomationInstall");
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 600);
		curl_setopt($ch, CURLOPT_REFERER, "http://".$domain);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);

		$postfields = array();
		$licensenumber = strtoupper(preg_replace('/[^0-9a-zA-Z]/i', '', $licensenumber));
		$postfields[] = "licensenumber=".urlencode(trim($licensenumber));
		$postfields[] = "project=eDirectory";
		$postfields[] = "domain=".urlencode(trim($domain));
		$postfields[] = "version=".urlencode(trim($version));

		curl_setopt($ch, CURLOPT_POSTFIELDS, implode("&", $postfields));
		$curl_response = curl_exec($ch);

		if (curl_errno($ch) || curl_error($ch)) {
			$message = "Software Registration Error: 30100<br />(".curl_errno($ch).") ".curl_error($ch)."";
			//echo __LINE__.PHP_EOL;
			$activationerror = 1;

			// Send mail with activation error
			$mail_content  = "===========================================================".PHP_EOL;
			$main_content .= "Activation Error on Automation".PHP_EOL;
			$mail_content .= "Customer URL..: ".$domain.PHP_EOL;
			$mail_content .= "DB Name.......: ".$db_name.PHP_EOL;
			$mail_content .= "License Number: ".$licensenumber.PHP_EOL;
			$mail_content .= "eDir Version..: ".$version.PHP_EOL;
			$mail_content .= "Message.......: ".$message.PHP_EOL;
			$mail_content .= "CURL Response.: ".$curl_response.PHP_EOL;
			$mail_content .= "===========================================================";
			mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Error',$mail_content);

			return false;
		} else {
			curl_close($ch);
			if ($curl_response) {
				if (strpos($curl_response, "success=") !== false) {

					$curl_response = str_replace("success=", "", $curl_response);
					$activationcode = $curl_response;

					// Send mail with activation error
					$mail_content  = "===========================================================".PHP_EOL;
					$main_content .= "Activation Done on Automation".PHP_EOL;
					$mail_content .= "Customer URL..: ".$domain.PHP_EOL;
					$mail_content .= "DB Name.......: ".$db_name.PHP_EOL;
					$mail_content .= "License Number: ".$licensenumber.PHP_EOL;
					$mail_content .= "eDir Version..: ".$version.PHP_EOL;
					$mail_content .= "Message.......: ".$message.PHP_EOL;
					$mail_content .= "CURL Response.: ".$curl_response.PHP_EOL;
					$mail_content .= "===========================================================";
					mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Done',$mail_content);

				} elseif (strpos($curl_response, "fail=") !== false) {

					$curl_response = str_replace("fail=", "", $curl_response);
					$message = $curl_response;
					$activationerror = 1;
					$mail_content  = "===========================================================".PHP_EOL;
					$main_content .= "Activation Error on Automation".PHP_EOL;
					$mail_content .= "Customer URL..: ".$domain.PHP_EOL;
					$mail_content .= "DB Name.......: ".$db_name.PHP_EOL;
					$mail_content .= "License Number: ".$licensenumber.PHP_EOL;
					$mail_content .= "eDir Version..: ".$version.PHP_EOL;
					$mail_content .= "Message.......: ".$curl_response.PHP_EOL;
					$mail_content .= "CURL Response.: ".$curl_response.PHP_EOL;
					$mail_content .= "===========================================================";
					mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Error',$mail_content);
					return false;

				} else {
					$message = "Software Registration Error: 30300";
					$activationerror = 1;
					//echo $message;
					//echo __LINE__.PHP_EOL;
					// Send mail with activation error
					$mail_content  = "===========================================================".PHP_EOL;
					$main_content .= "Activation Error on Automation".PHP_EOL;
					$mail_content .= "Customer URL..: ".$domain.PHP_EOL;
					$mail_content .= "DB Name.......: ".$db_name.PHP_EOL;
					$mail_content .= "License Number: ".$licensenumber.PHP_EOL;
					$mail_content .= "eDir Version..: ".$version.PHP_EOL;
					$mail_content .= "Message.......: ".$message.PHP_EOL;
					$mail_content .= "CURL Response.: ".$curl_response.PHP_EOL;
					$mail_content .= "===========================================================";
					mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Error',$mail_content);
					return false;
				}

			} else {
				$message = "Software Registration Error: 30200";
				$activationerror = 1;
				// Send mail with activation error
				$mail_content  = "===========================================================".PHP_EOL;
				$main_content .= "Activation Error on Automation".PHP_EOL;
				$mail_content .= "Customer URL..: ".$domain.PHP_EOL;
				$mail_content .= "DB Name.......: ".$db_name.PHP_EOL;
				$mail_content .= "License Number: ".$licensenumber.PHP_EOL;
				$mail_content .= "eDir Version..: ".$version.PHP_EOL;
				$mail_content .= "Message.......: ".$message.PHP_EOL;
				$mail_content .= "CURL Response.: ".$curl_response.PHP_EOL;
				$mail_content .= "===========================================================";
				mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Error',$mail_content);
				return false;
			}

		}

	}


	if (!$activationerror) {

		if ((!$activationcode) || ($activationcode != getActivationCode($licensenumber, $domain, $version))) {
	        

			//echo $activationcode."<br>";
			//echo getActivationCode($licensenumber, $domain, $version)."<br>";


			$message = "Wrong license number and/or activation code!";
			$activationerror = 1;
			//echo $message;
			//echo __LINE__.PHP_EOL;
			// Send mail with activation error
			$mail_content  = "===========================================================".PHP_EOL;
			$main_content .= "Activation Error on Automation".PHP_EOL;
			$mail_content .= "Customer URL...: ".$domain.PHP_EOL;
			$mail_content .= "DB Name........: ".$db_name.PHP_EOL;
			$mail_content .= "License Number.: ".$licensenumber.PHP_EOL;
			$mail_content .= "eDir Version...: ".$version.PHP_EOL;
			$mail_content .= "Message........: ".$message.PHP_EOL;
			$mail_content .= "Activation Code: ".$activationcode.PHP_EOL;
			$mail_content .= "Get Act. Code..: ".getActivationCode($licensenumber, $domain, $version).PHP_EOL;
			$mail_content .= "===========================================================";
			mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Error',$mail_content);
			return false;

		} else {

			if (!softwareRegistration($licensenumber, $domain, $version, $activationcode,$db_name)) {

				$message = "Wrong registration! Please try again!";
				//echo $message;
				$activationerror = 1;
				//echo __LINE__.PHP_EOL;
				$mail_content  = "===========================================================".PHP_EOL;
				$main_content .= "Activation Error on Automation".PHP_EOL;
				$mail_content .= "Customer URL...: ".$domain.PHP_EOL;
				$mail_content .= "DB Name........: ".$db_name.PHP_EOL;
				$mail_content .= "License Number.: ".$licensenumber.PHP_EOL;
				$mail_content .= "eDir Version...: ".$version.PHP_EOL;
				$mail_content .= "Message........: ".$message.PHP_EOL;
				$mail_content .= "===========================================================";
				mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Error',$mail_content);	
				return false;

			} else {

				$activationdone = 1;
				$mail_content  = "===========================================================".PHP_EOL;
				$main_content .= "Activation Error on Automation".PHP_EOL;
				$mail_content .= "Customer URL...: ".$domain.PHP_EOL;
				$mail_content .= "DB Name........: ".$db_name.PHP_EOL;
				$mail_content .= "License Number.: ".$licensenumber.PHP_EOL;
				$mail_content .= "eDir Version...: ".$version.PHP_EOL;
				$mail_content .= "Message........: Activation Done!".PHP_EOL;
				$mail_content .= "===========================================================";
				mail('rodrigo.apetito@arcasolutions.com','[AUTOMATION INSTALL] - Activation Done',$mail_content);	
				return true;

			}

		}

	}

}
?>