Skip to content

Instantly share code, notes, and snippets.

@ashleydw
Created June 11, 2011 21:44
Show Gist options
  • Save ashleydw/1020992 to your computer and use it in GitHub Desktop.
Save ashleydw/1020992 to your computer and use it in GitHub Desktop.
Uploading backup archives via CLI to Google Docs
<?php
/**
* A simple cron to get the newest .tar.gz file from a backup folder and upload to Google Docs.
*
* @version 1
* @author Ashley White, http://www.needathinkle.com/
* @license http://creativecommons.org/licenses/by-sa/3.0/
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_include_path('/home/library/');
require 'Zend/Loader/Autoloader.php';
Crons::backupsToGDocs();
final class Crons {
//Server folder to check
const FOLDER = '/backups';
const EMAIL = '';
const PASS = '';
const COLLECTION_NAME = 'sql_dumps';
const COLLECTION_ID = false; //If you know the folder ID you should set it here
//Log types
const MAIL = true;
const LOG = true;
const SESSION_URI = 'https://docs.google.com/feeds/upload/create-session/default/private/full';
const COLLECTION_URI = 'https://docs.google.com/feeds/default/private/full/folder%3Aroot/contents/-/folder';
const COLLECTION_ID_PATH = 'https://docs.google.com/feeds/id/folder%3A';
const FOLDER_URI = '/folder:%s/contents'; //Ready for sprintf
private static $_messages = array();
private static function _setUp() {
if(php_sapi_name() != 'cli' || !empty($_SERVER['REMOTE_ADDR']))
self::_error('Script must be called from cli');
Zend_Loader_Autoloader::getInstance();
}
private static function messages() {
echo "\n";
echo implode("\n", self::$_messages);
echo "\n";
}
private static function email($subject = '') {
$mail = new Zend_Mail('utf-8');
$mail->addTo(self::EMAIL);
$mail->setSubject('Backup Cron: '.date('d-m-Y H:i:s').'. '.$subject);
$mail->setBodyHtml(implode("<br />", self::$_messages));
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
'auth'=>'login',
'username'=>self::EMAIL,
'password'=>self::PASS,
'ssl'=>'tls'
));
$mail->send($transport);
self::$_messages[] = 'Log sent to: '.self::EMAIL;
}
private function _error($error) {
echo implode("\n", self::$_messages);
echo "\n";
echo $error;
echo "\n----------------\n";
exit;
}
public function backupsToGDocs() {
self::_setUp();
self::$_messages[] = '----------------';
self::$_messages[] = 'Starting backup to GDocs: '.date('d-m-Y H:i:s');
if(!is_dir(self::FOLDER))
self::_error(self::FOLDER.' isn\'t a directory');
$dir = glob(self::FOLDER.'*.tar.gz', GLOB_ERR);
if(!$dir)
self::_error(self::FOLDER.' couldn\'t glob directory, Maybe openbase_dir is running?: '.ini_get('open_basedir'));
if(is_array($dir) && count($dir) > 0) {
//Grab the zip file
$files = array();
foreach($dir as $file) {
if(!$file || $file == '.' || $file == '..' || is_dir($file)) continue;
$files[] = $file;
}
usort($files, function($a, $b) {
return filectime($a) < filectime($b);
});
$latest = $files[0];
$filename = str_replace(self::FOLDER, '', $latest);
self::$_messages[] = 'Processing file: '.$filename;
//Send to GDocs
$result = false;
try {
$client = Zend_Gdata_ClientLogin::getHttpClient(self::EMAIL, self::PASS, Zend_Gdata_Docs::AUTH_SERVICE_NAME);
$docs = new Zend_Gdata_Docs($client);
$docs->setMajorProtocolVersion(3);
//Search Google Doc collections for collection
//If you run this once, the ID will be displayed - you can store this in the CONST to skip this step
$folder = '';
if(self::COLLECTION_NAME && !self::COLLECTION_ID) {
self::$_messages[] = 'Processing collections, looking for: '.self::COLLECTION_NAME;
$result = $docs->getFeed(self::COLLECTION_URI);
foreach($result as $collection) {
if($collection->getTitle()->getText() == self::COLLECTION_NAME) {
$ID = str_replace(self::COLLECTION_ID_PATH, '', $collection->getId());
self::$_messages[] = 'Found collection, ID: '.$ID;
$folder = sprintf(self::FOLDER_URI, $collection->getContent()->getSrc());
break;
}
}
}
if(self::COLLECTION_ID) {
self::$_messages[] = 'Collection ID given: '.self::COLLECTION_ID;
$folder = sprintf(self::FOLDER_URI, self::COLLECTION_ID);
}
//Create the session
$result = $docs->performHttpRequest('POST', self::SESSION_URI.$folder, array(
'GData-Version'=>'3.0',
'Content-Length'=>0,
'Content-Type'=>'application/x-gzip',
'Slug'=>$filename,
'X-Upload-Content-Type'=>'application/x-gzip',
'X-Upload-Content-Length'=>filesize($latest)
), '', 'application/x-gzip');
if($result) {
$headers = $result->getHeaders();
self::$_messages[] = 'Session created.';
//Send file
$result = $docs->uploadFile($latest,
'Backup: '.$filename,
'application/x-gzip',
$headers['Location']);
} else {
self::$_messages[] = 'Session creation failed.';
}
} catch (Zend_Gdata_App_HttpException $e) {
self::$_messages[] = 'Error processing file: '.$e->getMessage();
}
//Close
if($result)
self::$_messages[] = $result = 'File upload successful.';
else
self::$_messages[] = $result = 'An error occurred.';
self::$_messages[] = 'Cron finished: '.date('d-m-Y H:i:s');
} else {
self::$_messages[] = self::FOLDER.' was empty. Nothing to do.';
}
self::$_messages[] = '----------------';
if(self::MAIL)
self::email($result);
if(self::LOG)
self::messages();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment