Backup and Restore - Code Sample
You may want to programmatically back up and restore your site if:
- Backup and restore isn't working via the Nitro Studio UI.
- You're unable to copy generated backup XML to the clipboard due to the backup size.
- You're unable to restore via the UI because the XML is too large for the request.
When restoring a backup, you can manually edit the XML file to remove unneeded data. Show me more
For example, if you have one sandbox and multiple production environments, you may want to restore only certain items from the backup. You can do this by manually editing the XML. Leave the items you want to restore in the XML and remove everything that you don't want to restore. So, to remove a mission, you would remove everything inside the <Challenge> tag (located between the <challenges></challenges> tags).
Show the edited XML for a mission that you do not want to restore
Before
Copy
<challenges>
<Challenge id="1234" clientId="123456|-470|34504" name="Experience Building" activeFlag="1" featuredFlag="0" callbackFlag="0" serviceType="1" order="0" pointCategory="Points" iconUrl="https://s3.amazonaws.com/bunchball_images/9e40c/userUploadpng189.png" thumbUrl="https://s3.amazonaws.com/bunchball_images/9e840c/userUploadpng152.png" fullUrl="https://s3.amazonaws.com/bunchball_images/9e805f4ca00c/userUploadpng158.png" pointAward="200" dateIssued="1450686540" applyMultiplier="0" repeatable="0" hideUntilEarned="0" pointCategoryId="10" customData="ORDER=12" tags="" startTime="1450686540" endTime="0" ruleMatchType="0" prereqMatchType="or" preferences="" preferenceValues="" preferencesMatchType="or" groupFlag="0" groupPointAward="0" dailyAchievementLimit="0" folderId="3338" activeLocales="" version="5.2">
<rules>
<Rule id="5432" clientId="123465|554|53930" tagId="10122" actionTag="2a1" operator="GE" description="To receive credit, you must to complete 5 Experience-building courses. Please refer to the User Guide for guidance by clicking on the <b>GO button</b>. Once you have completed a topic, please send your completion certificate to the team at <a href="mailto:email@email.com?subject=Certificate of completion&body=Please find attached the certificate for course completion" target="_blank"&email@email.com.</a>" goal="1" timeRange="3600" type="count" sortOrder="0" displayOrder="0" serviceType="customUrl" serviceActionType="custom url" customUrl="https://bunchball.com" url="http://bunchballe.com" prereqRuleIds="55178" prereqOperator="or" custom="10122" itemName="mode2_a1">
<Metadata/>
</Rule>
<Rule id="70105" clientId="1466|404|4224269" operator="" goal="0" type="operator" sortOrder="0" displayOrder="0" prereqRuleIds="55050" prereqOperator="and">
<Metadata/>
</Rule>
</rules>
<ChallengeRewards>
<ChallengeReward type="point" details="10|200" itemName="Points"/>
</ChallengeRewards>
</Challenge>
</challenges>
After
Copy
<challenges>
</challenges>
Example Code Snippets
Copy
<?php
class Nitro {
protected $_server;
protected $_apiKey;
protected $_userId;
protected $_sesKey;
protected $_url;
/**
* Connects to Nitro.
*
*@param $environment : Environment to connect to (String | Required)
*@param $apiKey : Apikey to be passed in (String | Required)
*@param $userId : UserId for session key generation to be passed in (String | Required)
*@param $password : Password for admin user (String | Required)
*/
public function __construct($environment, $apiKey, $userId, $password){
$this->setServer($environment);
$this->_apiKey = $apiKey;
$this->_userId = $userId;
$this->password = $password;
$this->setSessionKey();
}
/**
*Generate a session key. Will utilize the admin.login API call and generate a session that will last 15 mins (if there is no previous session).
*/
private function setSessionKey(){
$url = $this->_server."/nitro/json2?method=admin.login&apiKey=".$this->_apiKey."&userId=".$this->_userId."&password=".$this->password;
//Now let's Execute the login call
$response = json_decode($this->executePost($url), true);
$this->_sesKey = $response["Nitro"]["Login"]["sessionKey"];
}
/**
* Execute URL (POST)
*
* @param $url : URL to be passed in (String | Required)
* @param $data : Post data to send (array | Optional)
* @param $headers = Headers to send with request (array | Optional)
*/
public function executePost($url, $data = [], $headers = []){
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
/**
* Create Site Backup
*
* @param string : Name of the backup (Required)
*/
public function backup($name){
$this->_url = $this->_server . '/nitro/xml?sessionKey='. $this->_sesKey .'&method=admin.backupSiteConfig&name='.$name;
return $this->executePost($this->_url);
}
/**
* Execute site restore
*
* @param $XML : XML of the site backup (Required)
*/
public function restore($XML){
$data = ['method'=>'admin.restoreSiteConfig',
'data' => $XML,
'type' => '1',
'sessionKey' => $this->_sesKey,
'apiVersion' => '4.4',
'initial' => 'true'];
$headers = ["cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"];
return $this->executePost($this->getServer() . '/nitro/xml', http_build_query($data), $headers);
}
private function setServer($env){
return $this->_server = 'https://nitro.'.$env.'.bunchball.com';
}
public function getServer(){
return $this->_server;
}
}
Would be used as:
Copy
<?php
require_once('Nitro.php');
//Connection settings
$siteFrom = '<API KEY TO BACKUP FROM>';
$siteTo = '<API KEY TO RESTORE TO>';
$userName = '<ADMIN USER NAME>';
$password = '<ADMIN PASSWORD>';
$environmentFrom = '<ENVIRONMENT>'; //Sandbox, p1, etc.
$environmentTo = '<ENVIRONMENT>'; //Sandbox, p1, etc.
//Connect to Nitro
$nitroSiteFrom = new Nitro($environmentFrom, $siteFrom, $userName, $password);
$nitroSiteTo = new Nitro($environmentTo, $siteFrom, $userName, $password);
//Create the backup and remember the XML
$backupXML = $nitroSiteFrom->backup('<BACKUP NAME>');
//Restore the configuration from the backup
$restore = $nitroSiteTo->restore($backupXML);
//Dump response (should be XML)
var_dump($restore);
Copy
var request = require('request'); //Using request module for post request
"use strict";
module.exports = class NitroHandler{
constructor(apiKey, environment, user, password){
this.apiKey = apiKey;
this.env = environment;
this.user = user;
this.password = password;
this.setEnv();
}
/**
* Login to Nitro (generates sessionKey)
*
*/
login(){
this.url = this.env + '/nitro/json3?apiKey='+ this.apiKey +'&method=admin.login&userId='+ this.user +'&password='+ this.password;
return this.execute({json: true});
}
/**
* Execute current URL
*
* @param opt : options to send with request (object | optional)
*/
execute(opt = {}){
return new Promise((resolve) => {
let options = opt;
request.post(this.url, options, function(err, resp, body){
resolve(body);
});
});
}
/**
* Generate XML of site backup
*
* @param name : Backup name (string | required)
*/
backup(name){
this.url = this.env + '/nitro/xml?sessionKey=' + this.sessionKey + '&method=admin.backupSiteConfig&name=' + name;
return this.execute({});
}
/**
* Execute site restore
*
* @param xml : XML of the site backup (String | required)
*/
restore(xml){
this.url = this.env + '/nitro/xml';
let data = {
'initial': true,
'data': xml,
'type': '1',
'sessionKey': this.sessionKey,
'apiVersion': '4.4',
'method': 'admin.restoreSiteConfig'
};
let options = {
form: data,
}
return this.execute(options)
}
/****************
* Helper methods
***************/
/**
* Set the Nitro environment
*/
setEnv(){
this.env = 'https://nitro.'+ this.env + '.bunchball.com';
}
/**
* Set the sessionKey
*
* @param sessionKey : Sessionkey to set (String | required)
*/
setSessionKey(sessionKey){
this.sessionKey = sessionKey;
}
}
Would be used as:
Copy
var NitroHandler = require('./NitroHandler');
var co = require('co'); //Used for generator functions
var siteTo = '<API KEY TO BACKUP FROM>';
var siteFrom = '<API KEY TO RESTORE TO>';
var userName = '<ADMIN USER NAME>';
var password = '<ADMIN PASSWORD>';
var environmentFrom = '<ENVIRONMENT>'; //Sandbox, p1, etc.
var environmentTo = '<ENVIRONMENT>'; //Sandbox, p1, etc.
var nitroFrom = new NitroHandler(siteFrom, environmentFrom, userName, password);
var nitroTo = new NitroHandler(siteTo, environmentTo, userName, password);
return co(function*() {
let backupXml;
//Connect to Nitro from the API key you're generating the backup FROM
yield nitroFrom.login()
.then(result =>{
nitroFrom.setSessionKey(result.Nitro.Login.sessionKey);
})
.catch((error) => {
console.log(error);
});
//Generate the backup
yield nitroFrom.backup('backup')
.then(result =>{
backupXml = result; //Store our backup XML
})
.catch((error) => {
console.log(error);
});
//Connect to Nitro from the API key you're restoring the backup TO
yield nitroTo.login()
.then(result =>{
nitroTo.setSessionKey(result.response.login.sessionKey);
})
.catch((error) => {
console.log(error);
});
//Restore the backup
yield nitroTo.restore(backupXml)
.then(result =>{
console.log(result); //Display response
})
.catch((error) => {
console.log(error);
});
});
See also