Abstraction and factorization

This commit is contained in:
Shikiryu 2015-07-09 00:46:17 +02:00
parent 88a5b39d23
commit dbcd02c2af
9 changed files with 208 additions and 86 deletions

View File

@ -18,6 +18,22 @@ class Shikiryu_Backup_Abstract
$this->_streamsToBackup = array(); $this->_streamsToBackup = array();
} }
/**
* @return array
*/
public function getFilesToBackup()
{
return $this->_filesToBackup;
}
/**
* @return array
*/
public function getStreamsToBackup()
{
return $this->_streamsToBackup;
}
/** /**
* Add the current date with the given format into the files names * Add the current date with the given format into the files names
* *
@ -78,17 +94,32 @@ class Shikiryu_Backup_Abstract
return $this; return $this;
} }
function backupToEmail($to, $from, $objet, $mes) /**
*
* @param $name string
* @param $args mixed
*
* @return bool
*/
public function __call($name, $args)
{
if (substr($name,0,8) == 'backupTo') {
$type = substr($name, 8);
return Shikiryu_Backup_Transport_Factory::getAndSend($type, $this, $args);
}
}
/*function backupToEmail($to, $from, $object, $mes)
{ {
$email = new Shikiryu_Backup_Email(); $email = new Shikiryu_Backup_Email();
$email->addTo($to) $email->addTo($to)
->setFrom($from) ->setFrom($from)
->setSubject($objet) ->setSubject($object)
->setMessage($mes) ->setMessage($mes)
->setFiles($this->_filesToBackup) ->setFiles($this->_filesToBackup)
->setStreams($this->_streamsToBackup); ->setStreams($this->_streamsToBackup);
return $email->send(); return $email->send();
} }*/
function backupToDropbox() function backupToDropbox()
{ {
@ -103,6 +134,9 @@ class Shikiryu_Backup_Abstract
->send(); ->send();
} }
/**
* @param $folder
*/
function backupToFolder($folder) function backupToFolder($folder)
{ {
if (!empty($folder)) { if (!empty($folder)) {

View File

@ -11,8 +11,7 @@ class Shikiryu_Backup_Files extends Shikiryu_Backup_Abstract
{ {
parent::__construct(); parent::__construct();
if(!empty($filesToBackup) && is_array($filesToBackup)){ if(!empty($filesToBackup) && is_array($filesToBackup)){
$names = $filesToBackup; $names = array_map("basename",$filesToBackup);
array_walk($names, array($this, '_getNames'));
$this->_filesToBackup = array_combine($filesToBackup,$names); $this->_filesToBackup = array_combine($filesToBackup,$names);
} }
} }
@ -24,13 +23,12 @@ class Shikiryu_Backup_Files extends Shikiryu_Backup_Abstract
* *
* @return $this * @return $this
*/ */
function setFilePath($filestobackup = array()) function setFilePath($filesToBackup = array())
{ {
if(!empty($filestobackup) && is_array($filestobackup)) if(!empty($filesToBackup) && is_array($filesToBackup))
{ {
$names = $filestobackup; $names = array_map("basename",$filesToBackup);
array_walk($names, 'basename'); $this->_filesToBackup = array_combine($filesToBackup,$names);
$this->_filesToBackup = array_combine($filestobackup,$names);
} }
return $this; return $this;
} }

View File

@ -2,7 +2,8 @@
include_once dirname(__FILE__) . '/Abstract.php'; include_once dirname(__FILE__) . '/Abstract.php';
class Shikiryu_Backup_MYSQL extends Shikiryu_Backup_Abstract { class Shikiryu_Backup_MYSQL extends Shikiryu_Backup_Abstract
{
/** /**
* @var $_pdo PDO * @var $_pdo PDO

View File

@ -1,5 +1,22 @@
<?php <?php
class Shikiryu_Backup_Transport_Abstract { abstract class Shikiryu_Backup_Transport_Abstract
{
protected $backup;
protected $config;
public function __construct(Shikiryu_Backup_Abstract $backup)
{
$config = parse_ini_file(dirname(__FILE__).'/../config/config.ini');
$classname = get_class($this);
$type = substr($classname, strrpos($classname, '_')+1);
$this->config = $config[ucfirst(strtolower($type))];
$this->backup = $backup;
}
/**
* @return bool
*/
public abstract function send();
} }

View File

@ -1,14 +1,15 @@
<?php <?php
class Shikiryu_Backup_Email { class Shikiryu_Backup_Transport_Email extends Shikiryu_Backup_Transport_Abstract
{
private $_to; private $to;
private $_from; private $from;
private $_encoding; private $encoding;
private $_subject; private $subject;
private $_message; private $message;
private $_files; private $files;
private $_streams; private $streams;
public static $mimeTypes = array( public static $mimeTypes = array(
'txt' => 'text/plain', 'txt' => 'text/plain',
'htm' => 'text/html', 'htm' => 'text/html',
@ -138,10 +139,18 @@ class Shikiryu_Backup_Email {
} }
/** /**
* @param string $enc encoding of the mail * @param Shikiryu_Backup_Abstract $backup
*/ */
function __construct($enc = 'UTF-8') { public function __construct(Shikiryu_Backup_Abstract $backup) {
$this->_encoding = $enc; parent::__construct($backup);
$this->setFiles($this->backup->getFilesToBackup());
$this->setStreams($this->backup->getStreamsToBackup());
$this->to = $this->config['to'];
$this->from = $this->config['from'];
$this->encoding = $this->config['encoding'];
$this->subjet = $this->config['subject'];
$this->message = $this->config['message'];
$this->encoding = $this->config['encoding'];
} }
/** /**
@ -151,8 +160,9 @@ class Shikiryu_Backup_Email {
* *
* @return $this * @return $this
*/ */
function addTo($to) { private function addTo($to)
$this->_to = $to; {
$this->to = $to;
return $this; return $this;
} }
@ -163,8 +173,9 @@ class Shikiryu_Backup_Email {
* *
* @return $this * @return $this
*/ */
function setFrom($from) { private function setFrom($from)
$this->_from = $from; {
$this->from = $from;
return $this; return $this;
} }
@ -175,8 +186,9 @@ class Shikiryu_Backup_Email {
* *
* @return $this * @return $this
*/ */
function setSubject($sub) { private function setSubject($sub)
$this->_subject = strip_tags($sub); {
$this->subject = strip_tags($sub);
return $this; return $this;
} }
@ -187,21 +199,24 @@ class Shikiryu_Backup_Email {
* *
* @return $this * @return $this
*/ */
function setMessage($mes) { private function setMessage($mes)
$this->_message = strip_tags($mes); {
$this->message = strip_tags($mes);
return $this; return $this;
} }
function setFiles($files = array()) { private function setFiles($files = array())
{
if (is_array($files) && !empty($files)) { if (is_array($files) && !empty($files)) {
$this->_files = $files; $this->files = $files;
} }
return $this; return $this;
} }
function setStreams($streams = array()) { private function setStreams($streams = array())
{
if (is_array($streams) && !empty($streams)) { if (is_array($streams) && !empty($streams)) {
$this->_streams = $streams; $this->streams = $streams;
} }
return $this; return $this;
} }
@ -213,14 +228,14 @@ class Shikiryu_Backup_Email {
* *
* @return bool * @return bool
*/ */
function send() { public function send() {
// Checking files are selected // Checking files are selected
$zip = new ZipArchive(); // Load zip library $zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name $zip_name = time().".zip"; // Zip name
if($zip->open(dirname(__FILE__).'/bu/'.$zip_name, ZIPARCHIVE::CREATE)==TRUE) { if($zip->open(dirname(__FILE__).'/bu/'.$zip_name, ZIPARCHIVE::CREATE)==TRUE) {
if(!empty($this->_files)) { if(!empty($this->files)) {
foreach($this->_files as $file) foreach($this->files as $file)
{ {
$zip->addFile($file); // Adding files into zip $zip->addFile($file); // Adding files into zip
} }
@ -228,21 +243,21 @@ class Shikiryu_Backup_Email {
$zip->close(); $zip->close();
} }
$this->_files = array(dirname(__FILE__).'/bu/'.$zip_name=>dirname(__FILE__).'/bu/'.$zip_name); $this->files = array(dirname(__FILE__).'/bu/'.$zip_name=>dirname(__FILE__).'/bu/'.$zip_name);
$random_hash = md5(date('r', time())); $random_hash = md5(date('r', time()));
$headers = "From: " . $this->_from . "\r\nReply-To: " . $this->_from; $headers = "From: " . $this->from . "\r\nReply-To: " . $this->from;
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"" . $random_hash . "\""; $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"" . $random_hash . "\"";
$output = " $output = "
--$random_hash --$random_hash
Content-Type: text/plain; charset='" . strtolower($this->_encoding) . "' Content-Type: text/plain; charset='" . strtolower($this->encoding) . "'
Content-Transfer-Encoding: 8bit Content-Transfer-Encoding: 8bit
" . $this->_message . "\r\n"; " . $this->message . "\r\n";
if(!empty($this->_files)) if(!empty($this->files))
foreach($this->_files as $file=>$name) { foreach($this->files as $file=>$name) {
$name = end(explode('/', $name)); $name = end(explode('/', $name));
$output .= " $output .= "
--$random_hash --$random_hash
@ -253,8 +268,8 @@ Content-Disposition: attachment; filename=" . $name . "
" . chunk_split(base64_encode(file_get_contents($file))); " . chunk_split(base64_encode(file_get_contents($file)));
} }
if(!empty($this->_streams)) if(!empty($this->streams))
foreach($this->_streams as $name=>$stream) { foreach($this->streams as $name=>$stream) {
if(count(explode('.',$name))<2) $name = 'backup'.$name.'.txt'; if(count(explode('.',$name))<2) $name = 'backup'.$name.'.txt';
$output .= " $output .= "
--$random_hash --$random_hash
@ -265,7 +280,7 @@ Content-Disposition: attachment; filename=" . $name . "
" . chunk_split(base64_encode($stream)); " . chunk_split(base64_encode($stream));
} }
$output.="--$random_hash--"; $output.="--$random_hash--";
return mail($this->_to, $this->_subject, $output, $headers); return mail($this->to, $this->subject, $output, $headers);
} }
} }

View File

@ -1,74 +1,80 @@
<?php <?php
class Shikiryu_Backup_FTP { class Shikiryu_Backup_Transport_Ftp extends Shikiryu_Backup_Transport_Abstract
{
private $_path; private $path;
private $_connection; private $connection;
private $_files; private $files;
private $_streams; private $streams;
function __construct($server, $login, $pwd, $path='/') { public function __construct($backup, $server, $login, $pwd, $path='/') {
if ($path != '') { parent::__construct($backup);
$path = sprintf('/%s/', ltrim(rtrim($path, '/'),'/'));
// if (substr($path, 0, 1) != '/') $this->path = $this->config['path'];
// $path = '/' . $path; if (!empty($this->config['path'])) {
// if (substr($path, 0, -1) != '/') $this->path = sprintf('/%s/', ltrim(rtrim($this->config['path'], '/'),'/'));
// $path .= '/';
} }
$this->_path = $path;
$this->_connection = ftp_connect($server);
$login = ftp_login($this->_connection, $login, $pwd); $this->connection = ftp_connect($this->config['host']);
if (!$this->_connection || !$login) {
$login = ftp_login($this->connection, $this->config['login'], $this->config['password']);
if (!$this->connection || !$login) {
throw new Exception('Connexion FTP refusée.'); throw new Exception('Connexion FTP refusée.');
} }
$this->setFiles($this->backup->getFilesToBackup());
$this->setStreams($this->backup->getStreamsToBackup());
} }
function setFiles($files = array()) private function setFiles($files = array())
{ {
if (is_array($files) && !empty($files)) if (is_array($files) && !empty($files))
$this->_files = $files; $this->files = $files;
return $this; return $this;
} }
function setStreams($streams = array()) { private function setStreams($streams = array()) {
if (is_array($streams) && !empty($streams)) if (is_array($streams) && !empty($streams))
$this->_streams = $streams; $this->streams = $streams;
return $this; return $this;
} }
function send() public function send()
{ {
if (!empty($this->_files)){ $sent = true;
foreach ($this->_files as $file => $name) { if (!empty($this->files)){
$upload = ftp_put($this->_connection, $this->_path.$name, $file, FTP_ASCII); foreach ($this->files as $file => $name) {
// TODO PASSIVE MODE
$upload = ftp_put($this->connection, $this->path.$name, $file, FTP_ASCII);
if (!$upload) { if (!$upload) {
echo 'FTP upload manquée de '.$file.' vers '.$this->_path.$name; $sent = false;
echo 'FTP upload manquée de '.$file.' vers '.$this->path.$name;
} }
// else echo 'upload réussi de '.$file.' vers '.$this->_path.$name;
} }
} }
if (!empty($this->_streams)){ if (!empty($this->streams)){
foreach ($this->_streams as $name => $stream) { foreach ($this->streams as $name => $stream) {
if (count(explode('.', $name)) < 2) if (count(explode('.', $name)) < 2)
$name = 'backup' . $name . '.txt'; $name = 'backup' . $name . '.txt';
file_put_contents($name, $stream); file_put_contents($name, $stream);
$upload = ftp_put($this->_connection, $this->_path.$name, $name, FTP_ASCII); // TODO PASSIVE MODE
$upload = ftp_put($this->connection, $this->path.$name, $name, FTP_ASCII);
if (!$upload) { if (!$upload) {
echo 'FTP upload manquée de '.$name.' vers '.$this->_path.$name; echo 'FTP upload manquée de '.$name.' vers '.$this->_path.$name;
$sent = false;
} }
// else echo 'upload réussi de '.$name.' vers '.$this->_path.$name;
unlink($name); unlink($name);
} }
} }
} }
function __destruct() public function __destruct()
{ {
ftp_close($this->_connection); ftp_close($this->connection);
} }

20
Transport/Factory.php Normal file
View File

@ -0,0 +1,20 @@
<?php
class Shikiryu_Backup_Transport_Factory
{
/**
* @param $type
* @param Shikiryu_Backup_Abstract $backup
*
* @return bool
*/
public static function getAndSend($type, Shikiryu_Backup_Abstract $backup, $args = null) {
$class = sprintf('Shikiryu_Backup_Transport_%s', ucfirst($type));
if (class_exists($class)) {
/* @var $instance Shikiryu_Backup_Transport_Abstract */
$instance = new $class($backup, $args);
return $instance->send();
}
return false;
}
}

12
config/config.ini Normal file
View File

@ -0,0 +1,12 @@
[Email]
to=text@example.com
from=myserver@example.com
encoding=UTF-8
subject=[server.com] Backup
message=Hi,\n\nYou can find your backup in this mail.\n\nRegards,\nMyself.
[Ftp]
host=ftp.domain.com
login=login
password=password
folder=folder

View File

@ -1,14 +1,33 @@
<?php <?php
error_reporting(E_ALL); error_reporting(E_ALL);
include dirname(__FILE__) . '/Files.php'; define('TEST_FOLDER', dirname(__FILE__));
include dirname(__FILE__) . '/Mysql.php'; include TEST_FOLDER . '/../Files.php';
include TEST_FOLDER . '/../Mysql.php';
$backup = new Shikiryu_Backup_Files(array(dirname(__FILE__).'/newhtml.html')); // Test Backup file -> folder
// test 1
echo "starting test 1 \n";
$file = TEST_FOLDER.'/test1';
file_put_contents($file, 'test1');
echo file_exists($file) ? 'OK' : 'KO';
echo "\n";
$backup = new Shikiryu_Backup_Files(array($file));
$date = date('Ydm');
$backup->addDate($date)->backupToFolder('bu');
$backupFile = TEST_FOLDER.'/bu/'.$date.'.test1';
if (file_exists($backupFile)) {
echo 'OK';
unlink($backupFile);
} else {
die('KO - see what\'s in bu');
}
/*
$backup->addDate()->addTime()->backupToEmail('from@gmail.com', 'to@gmail.com', 'test class', 'coucou'); $backup->addDate()->addTime()->backupToEmail('from@gmail.com', 'to@gmail.com', 'test class', 'coucou');
$backup->addDate()->addTime()->backupToFTP('ftp.domain.com', 'login', 'password', '/folder'); $backup->addDate()->addTime()->backupToFTP('ftp.domain.com', 'login', 'password', '/folder');
$backup->backupToFolder('bu');
$backup2 = new Shikiryu_Backup_MYSQL('localhost', 'login', 'password', 'db'); $backup2 = new Shikiryu_Backup_MYSQL('localhost', 'login', 'password', 'db');
$backup2->fromTables(array('table1'))->addDate()->addTime(); $backup2->fromTables(array('table1'))->addDate()->addTime();
$backup2->backupToFolder('bu'); $backup2->backupToFolder('bu');
?> ?>
*/