漏洞说明

GreenCMS 存在一个安全漏洞,该漏洞影响版本 2.3.0603 及之前版本。

影响版本

GreenCMS ≤ 2.3.0603

代码结构

/

|--Addons 插件文件夹 (与OneThink高度兼容)

|-- 各个插件目录

|--Application 应用目录

|-- Admin 管理员模块

|-- Home 主模块

|-- Api 手机客户端API模块

|-- Common 通用基础模块

|-- Install 安装程序模块

|-- Weixin 微信公共平台API模块

|-- Core ThinkPHP 3.2.1 完整版 (有删减)

|-- Data 运行文件

|-- Backup 全站备份

|-- Cache 升级等工作的缓存

|-- DBbackup 数据库备份

|-- Install 安装文件

|-- Log hinkPHP框架Log

|-- Upgrade 升级文件

|-- Temp ThinkPHP框架Temp目录

|-- Extend 外部扩展文件夹

|-- GreenFinder Elfinder文件管理器

|-- PHPMailer 邮件发送类

|-- Ueditor 编辑器

|-- Public 公共文件夹

|-- 各个主题文件夹

|-- Upload 上传文件夹

|-- 不同类型的附件

//==

README

.htaccess

.gitignore

robots.txt

LICENSE.txt

//跳转文件

admin.php

weixin.php

install.php

//配置文件

const_config.php

version_config.php

db_config.php

//入口文件

index.php

分析

漏洞成因

框架特点

需要注意的是,这里的底层框架是TP框架

根据poc‘/index.php?m=admin&c=media&a=fileconnect’分析,在TP框架中或者说PHP的框架以及其他框架都大同小艺,m=admin这里的m代表的是目录:模块(Module)、c=media的c代表文件:控制器(Controller)、a=fileconnect的a代表方法:操作(Action)。

所以整体的意思就是在admin这个模块目录中控制器(Controller)目录找到meida文件
注意:在TP3.2中控制器的类名为:“控制器名字(就是media)+Controller(控制器)+.class.php”

所以要找的就是meidaController.class.php这个文件,最后在这个文件中找到fileconnect方法

漏洞地址

文件连接方法(MeidaController.class.php)

public function fileConnect()
{
    $roots = array('Upload/', 'Application/', 'Public/', ''); //
    $opts = $this->__array($roots);

    define('GreenCMS', 'GreenCMS');

    include WEB_ROOT . 'Extend/Elfinder/php/connector.php'; //包含elfinder自带php接口的入口文件
}

首先设置了四个目录:上传目录(Upload)、应用目录(Application)、公共资源目录(Public)、根目录(‘’),然后将目录数组转换为Elfinder所需要的配置格式,定义常量GreenCMS,最后连接器引入。

核心连接器(connector.php)

<?php

defined('GreenCMS') or exit();

error_reporting(0); // Set E_ALL for debuging

include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderConnector.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinder.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeDriver.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeLocalFileSystem.class.php';
/**
 * Simple function to demonstrate how to control file access using "accessControl" callback.
 * This method will disable accessing files/folders starting from '.' (dot)
 *
 * @param  string  $attr  attribute name (read|write|locked|hidden)
 * @param  string  $path  file path relative to volume root directory started with directory separator
 * @return bool|null
 **/
function access($attr, $path, $data, $volume) {
	return strpos(basename($path), '.') === 0       // if file/folder begins with '.' (dot)
		? !($attr == 'read' || $attr == 'write')    // set read+write to false, other (locked+hidden) set to true
		:  null;                                    // else elFinder decide it itself
}
$connector = new elFinderConnector(new elFinder($opts));
$connector->run();

首先是检测,检查是否定义了常量GreenCMS,没有定义就退出,然后是错误报告的设置:关闭所有错误报告,可以设置为E_ALL用于调试;包含了四个类:连接器类(elFinderConnector.class.php),用于处理请求和响应、核心类(elFinder.class.php),用于初始化和管理文件系统、卷驱动抽象类(elFinderVolumeDriver.class.php),定义了文件系统卷的通用接口、本地文件系统类驱动(elFinderVolumeLocalFileSystem.class.php)。然后检测以点开头的文件/文件夹:如.htaccess,.gitignore等。权限控制:对于点开头的文件,禁止读取和写入,但允许锁定和隐藏、其他文件,由Elfinder自行决定。最后就是连接器初始化和运行:创建Elfinder实例并传入配置选项$opts,通过连接器运行文件管理器。

核心文件(elFinder.class.php)

命令定义

这里代码较长一段一段的去分析
第一段:

protected $commands = array(
    'open'      => array('target' => false, 'tree' => false, 'init' => false, 'mimes' => false),
    'ls'        => array('target' => true, 'mimes' => false),
    'tree'      => array('target' => true),
    'parents'   => array('target' => true),
    'tmb'       => array('targets' => true),
    'file'      => array('target' => true, 'download' => false),
    'size'      => array('targets' => true),
    'mkdir'     => array('target' => true, 'name' => true),
    'mkfile'    => array('target' => true, 'name' => true, 'mimes' => false),
    'rm'        => array('targets' => true),
    'rename'    => array('target' => true, 'name' => true, 'mimes' => false),
    'duplicate' => array('targets' => true, 'suffix' => false),
    'paste'     => array('dst' => true, 'targets' => true, 'cut' => false, 'mimes' => false),
    'upload'    => array('target' => true, 'FILES' => true, 'mimes' => false, 'html' => false),
    'get'       => array('target' => true),
    'put'       => array('target' => true, 'content' => '', 'mimes' => false),
    'archive'   => array('targets' => true, 'type' => true, 'mimes' => false),
    'extract'   => array('target' => true, 'mimes' => false),
    'search'    => array('q' => true, 'mimes' => false),
    'info'      => array('targets' => true),
    'dim'       => array('target' => true),
    'resize'    => array('target' => true, 'width' => true, 'height' => true, 'mode' => false, 'x' => false, 'y' => false, 'degree' => false),
    'netmount'  => array('protocol' => true, 'host' => true, 'path' => false, 'port' => false, 'user' => true, 'pass' => true, 'alias' => false, 'options' => false)
);

这里一看就知道是一些命令,但是这些命令都定义了必需的参数,true表示必需,false表示可选
这里就有我们所用到的upload,然后还有后面去拓展的ls、mkdir等等

定义错误常量
public $mountErrors = array();

// Errors messages
const ERROR_UNKNOWN           = 'errUnknown';
const ERROR_UNKNOWN_CMD       = 'errUnknownCmd';
const ERROR_CONF              = 'errConf';
const ERROR_CONF_NO_JSON      = 'errJSON';
const ERROR_CONF_NO_VOL       = 'errNoVolumes';
const ERROR_INV_PARAMS        = 'errCmdParams';
const ERROR_OPEN              = 'errOpen';
const ERROR_DIR_NOT_FOUND     = 'errFolderNotFound';
const ERROR_FILE_NOT_FOUND    = 'errFileNotFound';     // 'File not found.'
const ERROR_TRGDIR_NOT_FOUND  = 'errTrgFolderNotFound'; // 'Target folder "$1" not found.'
const ERROR_NOT_DIR           = 'errNotFolder';
.....
const ERROR_SESSION_EXPIRES 	= 'errSessionExpires';

	const ERROR_CREATING_TEMP_DIR 	= 'errCreatingTempDir';
	const ERROR_FTP_DOWNLOAD_FILE 	= 'errFtpDownloadFile';
	const ERROR_FTP_UPLOAD_FILE 	= 'errFtpUploadFile';
	const ERROR_FTP_MKDIR 		= 'errFtpMkdir';
	const ERROR_ARCHIVE_EXEC 	= 'errArchiveExec';
	const ERROR_EXTRACT_EXEC 	= 'errExtractExec';

这里定义了错误常量,覆盖了上面文件操作的各种错误场景,因代码过长不全部展示。

elFinder类构造方法(__construct)
public function __construct($opts) {
    if (session_id() == '') {
       session_start();
    }

    $this->time  = $this->utime();
    $this->debug = (isset($opts['debug']) && $opts['debug'] ? true : false);
    $this->timeout = (isset($opts['timeout']) ? $opts['timeout'] : 0);
    
    setlocale(LC_ALL, !empty($opts['locale']) ? $opts['locale'] : 'en_US.UTF-8');

    // bind events listeners
    if (!empty($opts['bind']) && is_array($opts['bind'])) {
       foreach ($opts['bind'] as $cmd => $handler) {
          $this->bind($cmd, $handler);
       }
    }

    if (!isset($opts['roots']) || !is_array($opts['roots'])) {
       $opts['roots'] = array();
    }

    // check for net volumes stored in session
    foreach ($this->getNetVolumes() as $root) {
       $opts['roots'][] = $root;
    }

    // "mount" volumes
    foreach ($opts['roots'] as $i => $o) {
       $class = 'elFinderVolume'.(isset($o['driver']) ? $o['driver'] : '');

       if (class_exists($class)) {
          $volume = new $class();

          if ($volume->mount($o)) {
             // unique volume id (ends on "_") - used as prefix to files hash
             $id = $volume->id();
             
             $this->volumes[$id] = $volume;
             if (!$this->default && $volume->isReadable()) {
                $this->default = $this->volumes[$id]; 
             }
          } else {
             $this->mountErrors[] = 'Driver "'.$class.'" : '.implode(' ', $volume->error());
          }
       } else {
          $this->mountErrors[] = 'Driver "'.$class.'" does not exists';
       }
    }

    // if at least one readable volume - ii desu >_<
    $this->loaded = !empty($this->default);
}
第1-3行:会话初始化
public function __construct($opts) {
    if (session_id() == '') {
       session_start();
    }

检查会话是否已启动

第4-5行:性能监控和调试设置
$this->time  = $this->utime();
$this->debug = (isset($opts['debug']) && $opts['debug'] ? true : false);

这是获取当前的微妙时间,以及控制是否开启调试模式

第6行:会话超时设置
$this->timeout = (isset($opts['timeout']) ? $opts['timeout'] : 0);

设置会话超时时间(秒),默认值是0表示不启用超时

第8行:区域设置
setlocale(LC_ALL, !empty($opts['locale']) ? $opts['locale'] : 'en_US.UTF-8');

设置系统区域,字符编码处理,默认值:en_US.UTF-8

第11-15行:事件监听绑定
if (!empty($opts['bind']) && is_array($opts['bind'])) {
    foreach ($opts['bind'] as $cmd => $handler) {
       $this->bind($cmd, $handler);
    }
}

允许外部注册命令执行前后的钩子函数,用于日志记录、权限检查、数据过滤等

第17-19行:根目录配置验证
if (!isset($opts['roots']) || !is_array($opts['roots'])) {
    $opts['roots'] = array();
}

确保roots配置项存在且为数组

第22-24行:网络卷恢复
foreach ($this->getNetVolumes() as $root) {
    $opts['roots'][] = $root;
}

从会话中恢复之前挂载的网络卷,$this->getNetVolumes():从$_SESSION['elFinderNetVolumes']获取配置

第27-46行:卷挂载核心逻辑
// "mount" volumes
foreach ($opts['roots'] as $i => $o) {
    $class = 'elFinderVolume'.(isset($o['driver']) ? $o['driver'] : '');

根据驱动名构造类名(如 elFinderVolumeLocalFileSystem);如果未指定驱动,使用空字符串(通常默认为本地文件系统)

if (class_exists($class)) {
    $volume = new $class();

确保驱动类可用;实例化:创建卷对象

if ($volume->mount($o)) {
    // unique volume id (ends on "_") - used as prefix to files hash
    $id = $volume->id();
    
    $this->volumes[$id] = $volume;

$volume->mount($o):挂载卷,应用配置选项,将成功挂载的卷存入 $this->volumes 数组

if (!$this->default && $volume->isReadable()) {
    $this->default = $this->volumes[$id]; 
}

将第一个可读的卷设为默认卷;$volume->isReadable():检查卷是否具有读权限

} else {
          $this->mountErrors[] = 'Driver "'.$class.'" : '.implode(' ', $volume->error());
       }
    } else {
       $this->mountErrors[] = 'Driver "'.$class.'" does not exists';
    }
}

挂载失败时记录错误信息,但不中断其他卷的挂载,记录类不存在的错误

第49-50行:加载状态确认
// if at least one readable volume - ii desu >_<
    $this->loaded = !empty($this->default);
}

至少有一个可读卷标为一家在,决定elFinder是否能正常工作

加载状态和版本号
/**
 * Return true if fm init correctly
 *
 * @return bool
 * @author Dmitry (dio) Levashov
 **/
public function loaded() {
    return $this->loaded;
}

/**
 * Return version (api) number
 *
 * @return string
 * @author Dmitry (dio) Levashov
 **/
public function version() {
    return $this->version;
}

两个方法(loaded()、version()),他们的作用就是返回加载状态和版本号

事件监听机制:添加事件监听器(bind方法)分析
命令解析逻辑
public function bind($cmd, $handler) {
    $cmds = $cmd == '*'
       ? array_keys($this->commands)
       : array_map('trim', explode(' ', $cmd));

这里是bind方法,这是一个事件监听器绑定方法,这里的‘*’表示绑定到所有命令,并且支持多命令,以空格分隔的命令列表。

监听器存储结构
foreach ($cmds as $cmd) {
    if ($cmd) {
       if (!isset($this->listeners[$cmd])) {
          $this->listeners[$cmd] = array();
       }

为每个命令创建空的监听器数组,

回调函数验证
if (is_callable($handler)) {
             $this->listeners[$cmd][] = $handler;
          }
       }
    }

    return $this;
}

is_callable()确保处理器可调用;返回$this:支持方法链

事件监听机制:移除事件监听器(unbind方法)分析
/**
 * Remove event (command exec) handler
 *
 * @param  string  command name
 * @param  string|array  callback name or array(object, method)
 * @return elFinder
 * @author Dmitry (dio) Levashov
 **/
public function unbind($cmd, $handler) {
    if (!empty($this->listeners[$cmd])) {
       foreach ($this->listeners[$cmd] as $i => $h) {
          if ($h === $handler) {
             unset($this->listeners[$cmd][$i]);
             return $this;
          }
       }
    }
    return $this;
}

这里是用于取消之前绑定的命令处理器

前期检查
public function unbind($cmd, $handler) {
    if (!empty($this->listeners[$cmd])) {

确保指定命令有绑定的监听器

精确匹配逻辑
foreach ($this->listeners[$cmd] as $i => $h) {
       if ($h === $handler) {
          unset($this->listeners[$cmd][$i]);
          return $this;
       }
    }
}

严格比较:$h === $handler 确保完全相同的回调引用

找到并移除第一个匹配项后立即返回,使用unset()是保持数组索引

命令存在性检查方法(commandExists方法)
/**
 * Return true if command exists
 *
 * @param  string  command name
 * @return bool
 * @author Dmitry (dio) Levashov
 **/
public function commandExists($cmd) {
    return $this->loaded && isset($this->commands[$cmd]) && method_exists($this, $cmd);
}

首先这是用于验证指定的elFinder命令是否可用

$this->loaded(系统加载状态检查)前提条件:elFinder必须成功初始化,至少有一个可读的存储卷挂载成功

isset($this->commands[$cmd])(命令定义检查)配置验证:检查命令是否在预定义命令列表中

method_exists($this,$cmd)(方法实现检查)实现验证:确保命令有对应的类方法实现,而且每个命令都对应一个同名的protected方法

commandArgsList方法
public function commandArgsList($cmd) {
    return $this->commandExists($cmd) ? $this->commands[$cmd] : array();
}

他的作用就是获取指定命令的参数要求定义,返回值是命令参数配置数组或空数组

session_expires()方法
private function session_expires() {
    
    if (!isset($_SESSION['LAST_ACTIVITY'])) {
       $_SESSION['LAST_ACTIVITY'] = time();
       return false;
    }

    if ( ($this->timeout > 0) && (time() - $_SESSION['LAST_ACTIVITY'] > $this->timeout) ) {
       return true;
    }

    $_SESSION['LAST_ACTIVITY'] = time();
    return false;  
}
会话初始化
private function session_expires() {
    
    if (!isset($_SESSION['LAST_ACTIVITY'])) {
       $_SESSION['LAST_ACTIVITY'] = time();
       return false;
    }

这个表示的是设置初始活动时间戳,返回值false代表会话未过期

过期检测逻辑
if ( ($this->timeout > 0) && (time() - $_SESSION['LAST_ACTIVITY'] > $this->timeout) ) {
    return true;
}

超时检查:$this->timeout > 0 确保启用了超时机制

时间计算:当前时间与最后活动时间的差值

过期判定:超过设定的超时时间返回 true

活动时间更新
$_SESSION['LAST_ACTIVITY'] = time();
    return false;  
}

每次检查都会更新最后活动时间,用户有活动时会自动延长会话有效期

elFinder核心命令执行方法(exec方法)
/**
 * Exec command and return result
 *
 * @param  string  $cmd  command name
 * @param  array   $args command arguments
 * @return array
 * @author Dmitry (dio) Levashov
 **/
public function exec($cmd, $args) {
    
    if (!$this->loaded) {
       return array('error' => $this->error(self::ERROR_CONF, self::ERROR_CONF_NO_VOL));
    }

    if ($this->session_expires()) {
       return array('error' => $this->error(self::ERROR_SESSION_EXPIRES));
    }
    
    if (!$this->commandExists($cmd)) {
       return array('error' => $this->error(self::ERROR_UNKNOWN_CMD));
    }
    
    if (!empty($args['mimes']) && is_array($args['mimes'])) {
       foreach ($this->volumes as $id => $v) {
          $this->volumes[$id]->setMimesFilter($args['mimes']);
       }
    }
    
    $result = $this->$cmd($args);
    
    if (isset($result['removed'])) {
       foreach ($this->volumes as $volume) {
          $result['removed'] = array_merge($result['removed'], $volume->removed());
          $volume->resetRemoved();
       }
    }
    
    // call handlers for this command
    if (!empty($this->listeners[$cmd])) {
       foreach ($this->listeners[$cmd] as $handler) {
          if (call_user_func_array($handler,array($cmd,&$result,$args,$this))) {
             // handler return true to force sync client after command completed
             $result['sync'] = true;
          }
       }
    }
    
    // replace removed files info with removed files hashes
    if (!empty($result['removed'])) {
       $removed = array();
       foreach ($result['removed'] as $file) {
          $removed[] = $file['hash'];
       }
       $result['removed'] = array_unique($removed);
    }
    // remove hidden files and filter files by mimetypes
    if (!empty($result['added'])) {
       $result['added'] = $this->filter($result['added']);
    }
    // remove hidden files and filter files by mimetypes
    if (!empty($result['changed'])) {
       $result['changed'] = $this->filter($result['changed']);
    }
    
    if ($this->debug || !empty($args['debug'])) {
       $result['debug'] = array(
          'connector' => 'php', 
          'phpver'    => PHP_VERSION,
          'time'      => $this->utime() - $this->time,
          'memory'    => (function_exists('memory_get_peak_usage') ? ceil(memory_get_peak_usage()/1024).'Kb / ' : '').ceil(memory_get_usage()/1024).'Kb / '.ini_get('memory_limit'),
          'upload'    => $this->uploadDebug,
          'volumes'   => array(),
          'mountErrors' => $this->mountErrors
          );
       
       foreach ($this->volumes as $id => $volume) {
          $result['debug']['volumes'][] = $volume->debug();
       }
    }
    
    foreach ($this->volumes as $volume) {
       $volume->umount();
    }
    
    return $result;
}
1.系统状态检查
public function exec($cmd, $args) {
    
    if (!$this->loaded) {
       return array('error' => $this->error(self::ERROR_CONF, self::ERROR_CONF_NO_VOL));
    }

确保elFinder已正确初始化;ERROR_CONF_NO_VOL-没有可用的存储卷

2.会话安全验证
if ($this->session_expires()) {
    return array('error' => $this->error(self::ERROR_SESSION_EXPIRES));
}

防止会话被长期占用;自动终止过期的会话

3.命令有效性验证
if (!$this->commandExists($cmd)) {
    return array('error' => $this->error(self::ERROR_UNKNOWN_CMD));
}

确保只执行预定义的命令;信息加载+命令定义+方法存在

4.MIME类型过滤设置
if (!empty($args['mimes']) && is_array($args['mimes'])) {
    foreach ($this->volumes as $id => $v) {
       $this->volumes[$id]->setMimesFilter($args['mimes']);
    }
}

允许客户端指定允许的文件类型(对所有存储卷生效);搜索时限制文件类型

5.命令执行核心
$result = $this->$cmd($args);

根据命令名调用对应方法;将客户端参数传递给命令处理器

6.已删除文件收集
if (isset($result['removed'])) {
    foreach ($this->volumes as $volume) {
       $result['removed'] = array_merge($result['removed'], $volume->removed());
       $volume->resetRemoved();
    }
}

从所有存储卷收集删除记录;清空各卷的删除记录缓存

7.事件监听器执行
// call handlers for this command
if (!empty($this->listeners[$cmd])) {
    foreach ($this->listeners[$cmd] as $handler) {
       if (call_user_func_array($handler,array($cmd,&$result,$args,$this))) {
          // handler return true to force sync client after command completed
          $result['sync'] = true;
       }
    }
}

执行绑定的命令处理器;&$result允许监听器修改返回结果;监听器返回true可强制客户端同步

8.删除结果优化
// replace removed files info with removed files hashes
if (!empty($result['removed'])) {
    $removed = array();
    foreach ($result['removed'] as $file) {
       $removed[] = $file['hash'];
    }
    $result['removed'] = array_unique($removed);
}

将完整的文件信息替换为文件哈希;减少网络传输数据量;确保哈希值唯一

9.结果过滤
// remove hidden files and filter files by mimetypes
if (!empty($result['added'])) {
    $result['added'] = $this->filter($result['added']);
}
// remove hidden files and filter files by mimetypes
if (!empty($result['changed'])) {
    $result['changed'] = $this->filter($result['changed']);
}

移除标记为隐藏的文件;基于配置过滤不允许的文件类型;确保返回给客户端的数据是安全的

10.调试信息收集
if ($this->debug || !empty($args['debug'])) {
    $result['debug'] = array(
       'connector' => 'php', 
       'phpver'    => PHP_VERSION,
       'time'      => $this->utime() - $this->time,
       'memory'    => (function_exists('memory_get_peak_usage') ? ceil(memory_get_peak_usage()/1024).'Kb / ' : '').ceil(memory_get_usage()/1024).'Kb / '.ini_get('memory_limit'),
       'upload'    => $this->uploadDebug,
       'volumes'   => array(),
       'mountErrors' => $this->mountErrors
       );
    
    foreach ($this->volumes as $id => $volume) {
       $result['debug']['volumes'][] = $volume->debug();
    }
}

执行时间、内存使用情况;php版本、存储卷状态;挂载错误、上传调试信息

11.资源清理返回
foreach ($this->volumes as $volume) {
       $volume->umount();
    }
    
    return $result;
}

清理各卷的资源占用;返回格式化后的命令执行结果

文件哈希到真实路径的转换方法(realpaht方法)
/**
 * Return file real path
 *
 * @param  string  $hash  file hash
 * @return string
 * @author Dmitry (dio) Levashov
 **/
public function realpath($hash) {
    if (($volume = $this->volume($hash)) == false) {
       return false;
    }
    return $volume->realpath($hash);
}

用于将elFinder内部的文件哈希转换为服务器上的实际文件路径

1.存储卷查找
if (($volume = $this->volume($hash)) == false) {
    return false;
}

$this->volume($hash)方法逻辑:elFinder的文件哈希包含卷IP前缀(TP_gree中的TP_);通过字符串前缀匹配找到对应的存储卷;返回false表示无效的哈希或卷不存在

2.真实路径获取
return $volume->realpath($hash);
网络卷配置获取(getNetVolumes方法)
/**
 * Return network volumes config.
 *
 * @return array
 * @author Dmitry (dio) Levashov
 */
protected function getNetVolumes() {
    return isset($_SESSION['elFinderNetVolumes']) && is_array($_SESSION['elFinderNetVolumes']) ? $_SESSION['elFinderNetVolumes'] : array();
}

用于从会话中检索已保存的网络存储卷配置

1.会话数据检查
return isset($_SESSION['elFinderNetVolumes']) && is_array($_SESSION['elFinderNetVolumes'])

isset()确保会话变量存在;is_array()确保数据是数组格式

2.降级
? $_SESSION['elFinderNetVolumes'] : array();

返回会话中的网络卷配置数组;返回空数组,笔迷null或false导致的后续错误

网络卷配置保存(saveNetVolumes方法)
/**
 * Save network volumes config.
 *
 * @param  array  $volumes  volumes config
 * @return void
 * @author Dmitry (dio) Levashov
 */
protected function saveNetVolumes($volumes) {
    $_SESSION['elFinderNetVolumes'] = $volumes;
}

将网络卷配置数组保存到PHP会话中,实现持久化。

规范化错误信息(error方法)
public function error() {
    $errors = array();

    foreach (func_get_args() as $msg) {
       if (is_array($msg)) {
          $errors = array_merge($errors, $msg);
       } else {
          $errors[] = $msg;
       }
    }
    
    return count($errors) ? $errors : array(self::ERROR_UNKNOWN);
}

使用 func_get_args() 接受任意数量的参数;自动展开数组参数,合并到错误列表中;当没有错误时返回未知错误常量

挂载网络卷(netmount($args)方法)
protected function netmount($args) {
    $options  = array();
    $protocol = $args['protocol'];
    $driver   = isset(self::$netDrivers[$protocol]) ? $protocol : '';
    $class    = 'elfindervolume'.$protocol;

    if (!$driver) {
       return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], self::ERROR_NETMOUNT_NO_DRIVER));
    }

    if (!$args['path']) {
       $args['path'] = '/';
    }

    foreach ($args as $k => $v) {
       if ($k != 'options' && $k != 'protocol' && $v) {
          $options[$k] = $v;
       }
    }

    if (is_array($args['options'])) {
       foreach ($args['options'] as $key => $value) {
          $options[$key] = $value;
       }
    }

    $volume = new $class();

    if ($volume->mount($options)) {
       $netVolumes        = $this->getNetVolumes();
       $options['driver'] = $driver;
       $netVolumes[]      = $options;
       $netVolumes        = array_unique($netVolumes);
       $this->saveNetVolumes($netVolumes);
       return array('sync' => true);
    } else {
       return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], implode(' ', $volume->error())));
    }

动态挂载网络存储卷

1.驱动检测和类名构造
protected function netmount($args) {
    $options  = array();
    $protocol = $args['protocol'];
    $driver   = isset(self::$netDrivers[$protocol]) ? $protocol : '';
    $class    = 'elfindervolume'.$protocol;

检查请求的协议是否在支持的驱动列表中;检查协议名构造对应的卷类名

2.驱动不存在错误处理
if (!$driver) {
    return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], self::ERROR_NETMOUNT_NO_DRIVER));
}

返回格式化的错误信息,包含主机地址和驱动不存在错误

3.路径默认值设置
if (!$args['path']) {
    $args['path'] = '/';
}

确保路径参数有默认值,避免空路径导致的错误

4.配置选项合并
foreach ($args as $k => $v) {
    if ($k != 'options' && $k != 'protocol' && $v) {
       $options[$k] = $v;
    }
}

if (is_array($args['options'])) {
    foreach ($args['options'] as $key => $value) {
       $options[$key] = $value;
    }
}

从 $args 中提取非协议和选项字段;合并 $args['options'] 中的配置;只包含有值的配置项

5.卷挂载和持久化
$volume = new $class();

    if ($volume->mount($options)) {
       $netVolumes        = $this->getNetVolumes();
       $options['driver'] = $driver;
       $netVolumes[]      = $options;
       $netVolumes        = array_unique($netVolumes);
       $this->saveNetVolumes($netVolumes);
       return array('sync' => true);
    } else {
       return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], implode(' ', $volume->error())));
    }

}

创建对应的网络卷实例;调用卷的 mount() 方法;保存配置到会话,返回同步标记;返回包含卷具体错误的错误信息