genilto/sbackup

一个创建的小层,用于抽象将备份发送到不同云服务的PHP方法。

2.0.3 2023-05-02 04:40 UTC

This package is auto-updated.

Last update: 2024-10-01 00:14:55 UTC


README

SBackup

一个使用PHP生成和发送备份到类似onedrive或dropbox的小工具。

适配器

SBackup没有适配器将无法工作。以下是迄今为止已实现的适配器。您需要在项目中使用上述适配器之一。

SBackup-Dropbox

用于与dropbox api工作的适配器。

https://github.com/genilto/sbackup-dropbox

SBackup-Onedrive

用于与onedrive api工作的适配器。

https://github.com/genilto/sbackup-onedrive

安装

要使用此库,您可以使用composer将其导入到项目中。首先要创建一个名为 sbackup-example 的项目文件夹,然后运行以下composer命令

composer require genilto/sbackup-dropbox

这将安装所有与dropbox一起工作的依赖项,包括我们的SBackup库!

如何使用

以下是使用该库的一个简单示例。在自己的项目中发挥创意。如果您愿意,可以克隆存储库中的示例: https://github.com/genilto/sbackup-example

测试环境

为了帮助我们轻松测试应用程序,我们可以使用docker-composer。它使用您想要的确切PHP版本创建环境非常简单且速度非常快。

请确保您已在系统上安装了docker和docker-compose。

在项目文件夹中创建一个名为 docker-compose.yml 的文件,并包含以下内容

version:  '3.8'

services:
  apache:
    image: php:8.1-apache
    container_name: apache
    restart: unless-stopped
    ports:
      - 86:80
    environment:
      - DROPBOX_CLIENT_ID=${DROPBOX_CLIENT_ID}
      - DROPBOX_CLIENT_SECRET=${DROPBOX_CLIENT_SECRET}
    volumes:
      - .:/var/www

记住用您的dropbox凭据替换 ${DROPBOX_CLIENT_ID}${DROPBOX_CLIENT_SECRET}

现在在项目文件夹中创建另一个名为 html 的文件夹,并在其中创建一个名为 index.php 的文件,包含以下内容

<!DOCTYPE  html>
<html  lang="pt-br">
<head>
<meta  charset="utf-8"/>
<title>SBackup tests!</title>
</head>
<body>
 <div  style="padding: 50px; text-align: center; max-width: 500px; margin: auto;">
  <h1  style="padding: 20px;">SBackup <small>Tests</small></h1>
  <div>
   <a href="auth.php">1 - Go to Authentication page</a>
  </div>
  <div>
   <a href="upload.php">2 - Go to Upload page</a>
  </div>
 </div>
</body>
</html>

现在您已经准备好运行以下命令

docker-compose up -d

它将启动一个docker容器,运行在https://:86上的apache和php。如果您看到 SBackup Tests! 页面,您就可以继续了。

基本配置

下一步需要做的是实例化所有必须注入到SBackup中的类,然后实例化SBackup类。在 html 文件夹中创建一个名为 backup.config.php 的文件,并包含以下内容

<?php
require_once ( __DIR__  .  '/../vendor/autoload.php' );

use  \genilto\sbackup\SBackup;
use  \genilto\sbackup\adapters\SBackupDropbox;
use  \genilto\sbackup\store\FileDataStore;
use  \genilto\sbackup\logger\SBLogger;

use  \Analog\Analog;
use  \Analog\Logger;

// Defines the default timezone
Analog::$timezone =  'America/Sao_Paulo';
date_default_timezone_set(Analog::$timezone);

if (!function_exists('createDefaultLogger')) {

 /**
 * Creates the default logger using Analog as Logger class
 * Any other PSR-3 Logger could be used
 *
 * @return  SBLogger
 */
 function  createDefaultSBackupLogger () {
  // Creates the Default Logger
  $logger =  new  Logger();
  // Define where to save the logs
  $currentDate =  date("Y-m-d");
  $logger->handler (__DIR__  .  "/$currentDate-sbackup.log");
  // Return a SBLogger instance
  return  new  SBLogger($logger, 3); // 3 - Full Logging
 }
}

/**
* Define the required APP information
*/
define("DROPBOX_CLIENT_ID",  getenv("DROPBOX_CLIENT_ID"));
define("DROPBOX_CLIENT_SECRET",  getenv("DROPBOX_CLIENT_SECRET"));

/**
* Instantiate all the required configuration classes
*/

// Here you can instantiate a class responsible for store our tokens
// We have implemented FileDataStore that store in simple php files
// but you can implement your own, for store in database for example, just implementing the interface \genilto\sbackup\store\DataStoreInterface
$SBDataStore = new FileDataStore(__DIR__  .  "/dropbox-config");

// The logger that will me used
$SBLogger = createDefaultSBackupLogger();

// Create the adapter class that will be used. In this example, our Dropbox adapter!
// Here we need to inform the Dropbox Client ID and Client Secret
$SBUploader = new SBackupDropbox($SBDataStore, $SBLogger, DROPBOX_CLIENT_ID, DROPBOX_CLIENT_SECRET);

// The main SBackup class that will the available to be used
$SBackup = new SBackup($SBUploader, $SBLogger);

注意:要获取 Dropbox Client IDDropbox Client Secret,您可以在 https://developer.dropbox.com 创建您的应用程序。

现在,您已经有了可用的 $SBackup 对象来处理您的备份!

身份验证

下一步是创建一个页面,允许您在dropbox中验证程序对您的账户。为此,您可以在 html 文件夹中创建一个名为 auth.php 的新文件,并包含以下内容

<?php
  
// In production, it is very important to create some kind of
// Authorization, blocking users that do not have access to authenticate with
// the cloud service, as dropbox.

// If anyone reachs this page, they could authenticate their 
// own account and then receive all your uploaded files!!

// Include the backup.config.php file so we have the $SBackup object available
require_once ( __DIR__  .  '/backup.config.php' );

?>
<!DOCTYPE  html>
<html  lang="pt-br">
<head>
<meta  charset="utf-8"/>
<title><?php  echo $SBackup->getAdapterName(); ?> - Authentication</title>
</head>
<body>
 <div  style="padding: 50px; text-align: center; max-width: 500px; margin: auto;">
  <h1  style="padding: 20px;">SBackup <small>Configuration</small></h1>
  <?php
  /**
  * Starts the authorization flow according to the adapter being used
  * 
  * @var  SBackup $SBackup
  */
  $SBackup->authorizationFlow();
  ?>
 </div>
</body>
</html>

如果您想立即测试身份验证,您可以通过 https://:86/auth.php 进行导航。

在那里,您必须遵循指示。

上传

如果您已经遵循了以下所有步骤,现在您已经准备好将文件上传到dropbox。为此,您可以在 html 文件夹中创建一个名为 upload.php 的新文件,并包含以下内容

<?php

require_once ( __DIR__ . '/backup.config.php' );

/**
 * Return the error description of the uploaded file
 * 
 * @param string $path
 * 
 * @return string|false The function returns the error description or false on failure.
 */
function getUploadErrorDescription ($uploadErrorCode) {
    $phpFileUploadErrors = array(
        0 => 'There is no error, the file uploaded with success',
        1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3 => 'The uploaded file was only partially uploaded',
        4 => 'No file was uploaded',
        6 => 'Missing a temporary folder',
        7 => 'Failed to write file to disk.',
        8 => 'A PHP extension stopped the file upload.',
    );

    if (isset($phpFileUploadErrors[$uploadErrorCode])) {
        return $phpFileUploadErrors[$uploadErrorCode];
    }
    return false;
}

?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title><?php echo $SBackup->getAdapterName(); ?> - Upload</title>
</head>
<body>
    <div style="padding: 50px; text-align: center; max-width: 500px; margin: auto;">
        <h1 style="padding: 20px;">SBackup <small>Testing upload to Dropbox</small></h1>

<?php

if (isset($_POST["doupload"]) && $_POST["doupload"] == "YES") {
    
    // echo "<pre>";
    // print_r ($_FILES);
    // echo "</pre>";

    $filename = null;
    $filePath = null;
    if (isset($_FILES['file']) && isset($_FILES['file']['name'])) {
        $attach = $_FILES['file'];

        if (!empty($attach['name'])) {
            $errorCode = isset($attach["error"]) ? $attach["error"] : 0;
            if ($errorCode !== UPLOAD_ERR_OK) {
                echo "Error uploading file: " . getUploadErrorDescription($errorCode);
            } else {
                $filename = $attach['name'];
                $filePath = $attach['tmp_name'];
            }
        }
    }
    if (!empty($filePath)) {
        /**
         * @var genilto\sbackup\SBackup $SBackup
         */

        $year = date("Y");
        $month = date("m");
        $destinationFolder = "/backups/$year/$month/";
        try {
            /**
             * @var \genilto\sbackup\models\SBackupFileMetadata $uploadedFile
             */
            $uploadedFile = $SBackup->upload($filePath, $destinationFolder, $filename, false);
            echo "<b>Result:</b> File <b>" . $uploadedFile->getName() . "</b> uploaded to Dropbox!<br><br>";
            echo "<b>Details:</b> " . $uploadedFile->toString();

        } catch (Exception $e) {
            echo "<b>ERROR: </b>" . $e->getMessage();
        }
    } else {
        echo "File must be informed!";
    }
}

?>      <div style="padding: 20px;">
            <form name="dropbox-upload" action="" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="doupload" value="YES">
                File: <input name="file" type="file" value="" />
                <button type="submit">Upload</button>
            </form>
        </div>
        <div style="padding: 10px;">
      <a href="index.php">Back</a>
     </div>
    </div>
</body>
</html>