Shikiryu_Backup/app/code/transport/SFTP.php

75 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2015-08-17 13:16:28 +02:00
<?php
namespace Shikiryu\Backup\Transport;
2021-06-30 16:00:24 +02:00
use Exception;
2015-08-17 13:16:28 +02:00
use phpseclib\Net\SFTP as LibSFTP;
2021-06-30 16:00:24 +02:00
use Shikiryu\Backup\Backup\BackupAbstract;
2015-08-17 13:16:28 +02:00
class Sftp extends TransportAbstract
{
2016-07-03 21:54:35 +02:00
/** @var string */
2015-08-17 13:16:28 +02:00
protected $host;
2016-07-01 21:59:39 +02:00
/** @var int */
2015-08-17 13:16:28 +02:00
protected $port = 22;
2016-07-01 21:59:39 +02:00
/** @var string */
2015-08-17 13:16:28 +02:00
protected $login;
2016-07-01 21:59:39 +02:00
/** @var string */
2015-08-17 13:16:28 +02:00
protected $password;
2016-07-01 21:59:39 +02:00
/** @var string */
2015-08-17 13:16:28 +02:00
protected $folder;
2016-07-03 21:54:35 +02:00
/** @var LibSFTP */
2015-08-17 13:16:28 +02:00
private $connection;
/**
2021-06-30 16:00:24 +02:00
* @param BackupAbstract $backup
2015-08-17 13:16:28 +02:00
* @param array $config
2021-06-30 16:00:24 +02:00
* @throws Exception
2015-08-17 13:16:28 +02:00
*/
public function __construct($backup, $config)
{
parent::__construct($backup, $config);
$this->connection = new LibSFTP($this->host, $this->port);
if (!$this->connection->login($this->login, $this->password)) {
2021-06-30 16:00:24 +02:00
throw new Exception(sprintf('I can\'t connect to the FTP %s', $this->host));
2015-08-17 13:16:28 +02:00
}
}
/**
* @return bool
2016-07-03 21:54:35 +02:00
*
2021-06-30 16:00:24 +02:00
* @throws Exception
2015-08-17 13:16:28 +02:00
*/
public function send()
{
$sent = true;
2019-01-25 22:19:50 +01:00
$files = $this->backup->getFilesToBackup();
2016-07-03 21:54:35 +02:00
if (!empty($files)) {
2015-08-17 13:16:28 +02:00
foreach ($files as $file => $name) {
$upload = $this->connection->put($this->folder.'/'.$name, $file, LibSFTP::SOURCE_LOCAL_FILE);
if (!$upload) {
$sent = false;
2016-07-03 21:54:35 +02:00
echo 'SFTP upload manqu<71>e de '.$file.' vers '.$this->folder.$name;
2015-08-17 13:16:28 +02:00
}
}
}
2019-01-25 22:19:50 +01:00
$streams = $this->backup->getStreamsToBackup();
2016-07-03 21:54:35 +02:00
if (!empty($streams)) {
2015-08-17 13:16:28 +02:00
foreach ($streams as $name => $stream) {
$upload = $this->connection->put($this->folder.'/'.$name, $stream);
if (!$upload) {
2019-01-25 22:19:50 +01:00
echo 'SFTP upload manquΓ©e de '.$name.' vers '.$this->folder.$name;
2015-08-17 13:16:28 +02:00
$sent = false;
}
}
}
if (!$sent) {
2021-06-30 16:00:24 +02:00
throw new Exception('At least an upload didnt work.');
2015-08-17 13:16:28 +02:00
}
return $sent;
}
2016-07-03 21:54:35 +02:00
}