<?php
/**
* Simple elFinder driver for MySQL.
*
* @author Dmitry (dio) Levashov
**/
class elFinderVolumeMySQL extends elFinderVolumeDriver
{
/**
* Driver id
* Must be started from letter and contains [a-z0-9]
* Used as part of volume id
*
* @var string
**/
protected $driverId = 'm';
/**
* Database object
*
* @var mysqli
**/
protected $db = null;
/**
* Tables to store files
*
* @var string
**/
protected $tbf = '';
/**
* Directory for tmp files
* If not set driver will try to use tmbDir as tmpDir
*
* @var string
**/
protected $tmpPath = '';
/**
* Numbers of sql requests (for debug)
*
* @var int
**/
protected $sqlCnt = 0;
/**
* Last db error message
*
* @var string
**/
protected $dbError = '';
/**
* This root has parent id
*
* @var boolean
*/
protected $rootHasParent = false;
/**
* Constructor
* Extend options with required fields
*
* @author Dmitry (dio) Levashov
*/
public function __construct()
{
$opts = array(
'host' => 'localhost',
'user' => '',
'pass' => '',
'db' => '',
'port' => null,
'socket' => null,
'files_table' => 'elfinder_file',
'tmbPath' => '',
'tmpPath' => '',
'rootCssClass' => 'elfinder-navbar-root-sql',
'noSessionCache' => array('hasdirs'),
'isLocalhost' => false
);
$this->options = array_merge($this->options, $opts);
$this->options['mimeDetect'] = 'internal';
}
/*********************************************************************/
/* INIT AND CONFIGURE */
/*********************************************************************/
/**
* Prepare driver before mount volume.
* Connect to db, check required tables and fetch root path
*
* @return bool
* @author Dmitry (dio) Levashov
**/
protected function init()
{
if (!($this->options['host'] || $this->options['socket'])
|| !$this->options['user']
|| !$this->options['pass']
|| !$this->options['db']
|| !$this->options['path']
|| !$this->options['files_table']) {
return $this->setError('Required options "host", "socket", "user", "pass", "db", "path" or "files_table" are undefined.');
}
$err = null;
if ($this->db = @new mysqli($this->options['host'], $this->options['user'], $this->options['pass'], $this->options['db'], $this->options['port'], $this->options['socket'])) {
if ($this->db && $this->db->connect_error) {
$err = $this->db->connect_error;
}
} else {
$err = mysqli_connect_error();
}
if ($err) {
return $this->setError(array('Unable to connect to MySQL server.', $err));
}
if (!$this->needOnline && empty($this->ARGS['init'])) {
$this->db->close();
$this->db = null;
return true;
}
$this->db->set_charset('utf8');
if ($res = $this->db->query('SHOW TABLES')) {
while ($row = $res->fetch_array()) {
if ($row[0] == $this->options['files_table']) {
$this->tbf = $this->options['files_table'];
break;
}
}
}
if (!$this->tbf) {
return $this->setError('The specified database table cannot be found.');
}
$this->updateCache($this->options['path'], $this->_stat($this->options['path']));
// enable command archive
$this->options['useRemoteArchive'] = true;
// check isLocalhost
$this->isLocalhost = $this->options['isLocalhost'] || $this->options['host'] === 'localhost' || $this->options['host'] === '127.0.0.1' || $this->options['host'] === '::1';
return true;
}
/**
* Set tmp path
*
* @return void
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
*/
protected function configure()
{
parent::configure();
if (($tmp = $this->options['tmpPath'])) {
if (!file_exists($tmp)) {
if (mkdir($tmp)) {
chmod($tmp, $this->options['tmbPathMode']);
}
}
$this->tmpPath = is_dir($tmp) && is_writable($tmp) ? $tmp : false;
}
if (!$this->tmpPath && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
$this->tmpPath = $tmp;
}
// fallback of $this->tmp
if (!$this->tmpPath && $this->tmbPathWritable) {
$this->tmpPath = $this->tmbPath;
}
$this->mimeDetect = 'internal';
}
/**
* Close connection
*
* @return void
* @author Dmitry (dio) Levashov
**/
public function umount()
{
$this->db && $this->db->close();
}
/**
* Return debug info for client
*
* @return array
* @author Dmitry (dio) Levashov
**/
public function debug()
{
$debug = parent::debug();
$debug['sqlCount'] = $this->sqlCnt;
if ($this->dbError) {
$debug['dbError'] = $this->dbError;
}
return $debug;
}
/**
* Perform sql query and return result.
* Increase sqlCnt and save error if occured
*
* @param string $sql query
*
* @return bool|mysqli_result
* @author Dmitry (dio) Levashov
*/
protected function query($sql)
{
$this->sqlCnt++;
$res = $this->db->query($sql);
if (!$res) {
$this->dbError = $this->db->error;
}
return $res;
}
/**
* Create empty object with required mimetype
*
* @param string $path parent dir path
* @param string $name object name
* @param string $mime mime type
*
* @return bool
* @author Dmitry (dio) Levashov
**/
protected function make($path, $name, $mime)
{
$sql = 'INSERT INTO %s (`parent_id`, `name`, `size`, `mtime`, `mime`, `content`, `read`, `write`, `locked`, `hidden`, `width`, `height`) VALUES (\'%s\', \'%s\', 0, %d, \'%s\', \'\', \'%d\', \'%d\', \'%d\', \'%d\', 0, 0)';
$sql = sprintf($sql, $this->tbf, $path, $this->db->real_escape_string($name), time(), $mime, $this->defaults['read'], $this->defaults['write'], $this->defaults['locked'], $this->defaults['hidden']);
// echo $sql;
return $this->query($sql) && $this->db->affected_rows > 0;
}
/*********************************************************************/
/* FS API */
/*********************************************************************/
/**
* Cache dir contents
*
* @param string $path dir path
*
* @return string
* @author Dmitry Levashov
**/
protected function cacheDir($path)
{
$this->dirsCache[$path] = array();
$sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime AS ts, f.mime, f.read, f.write, f.locked, f.hidden, f.width, f.height, IF(ch.id, 1, 0) AS dirs
FROM ' . $this->tbf . ' AS f
LEFT JOIN ' . $this->tbf . ' AS ch ON ch.parent_id=f.id AND ch.mime=\'directory\'
WHERE f.parent_id=\'' . $path . '\'
GROUP BY f.id, ch.id';
$res = $this->query($sql);
if ($res) {
while ($row = $res->fetch_assoc()) {
$id = $row['id'];
if ($row['parent_id'] && $id != $this->root) {
$row['phash'] = $this->encode($row['parent_id']);
}
if ($row['mime'] == 'directory') {
unset($row['width']);
unset($row['height']);
$row['size'] = 0;
} else {
unset($row['dirs']);
}
unset($row['id']);
unset($row['parent_id']);
if (($stat = $this->updateCache($id, $row)) && empty($stat['hidden'])) {
$this->dirsCache[$path][] = $id;
}
}
}
return $this->dirsCache[$path];
}
/**
* Return array of parents paths (ids)
*
* @param int $path file path (id)
*
* @return array
* @author Dmitry (dio) Levashov
**/
protected function getParents($path)
{
$parents = array();
while ($path) {
if ($file = $this->stat($path)) {
array_unshift($parents, $path);
$path = isset($file['phash']) ? $this->decode($file['phash']) : false;
}
}
if (count($parents)) {
array_pop($parents);
}
return $parents;
}
/**
* Return correct file path for LOAD_FILE method
*
* @param string $path file path (id)
*
* @return string
* @author Troex Nevelin
**/
protected function loadFilePath($path)
{
$realPath = realpath($path);
if (DIRECTORY_SEPARATOR == '\\') { // windows
$realPath = str_replace('\\', '\\\\', $realPath);
}
return $this->db->real_escape_string($realPath);
}
/**
* Recursive files search
*
* @param string $path dir path
* @param string $q search string
* @param array $mimes
*
* @return array
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
*/
protected function doSearch($path, $q, $mimes)
{
if (!empty($this->doSearchCurrentQuery['matchMethod'])) {
// has custom match method use elFinderVolumeDriver::doSearch()
return parent::doSearch($path, $q, $mimes);
}
$dirs = array();
$timeout = $this->options['searchTimeout'] ? $this->searchStart + $this->options['searchTimeout'] : 0;
if ($path != $this->root || $this->rootHasParent) {
$dirs = $inpath = array(intval($path));
while ($inpath) {
$in = '(' . join(',', $inpath) . ')';
$inpath = array();
$sql = 'SELECT f.id FROM %s AS f WHERE f.parent_id IN ' . $in . ' AND `mime` = \'directory\'';
$sql = sprintf($sql, $this->tbf);
if ($res = $this->query($sql)) {
$_dir = array();
while ($dat = $res->fetch_assoc()) {
$inpath[] = $dat['id'];
}
$dirs = array_merge($dirs, $inpath);
}
}
}
$result = array();
if ($mimes) {
$whrs = array();
foreach ($mimes as $mime) {
if (strpos($mime, '/') === false) {
$whrs[] = sprintf('f.mime LIKE \'%s/%%\'', $this->db->real_escape_string($mime));
} else {
$whrs[] = sprintf('f.mime = \'%s\'', $this->db->real_escape_string($mime));
}
}
$whr = join(' OR ', $whrs);
} else {
$whr = sprintf('f.name LIKE \'%%%s%%\'', $this->db->real_escape_string($q));
}
if ($dirs) {
$whr = '(' . $whr . ') AND (`parent_id` IN (' . join(',', $dirs) . '))';
}
$sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime AS ts, f.mime, f.read, f.write, f.locked, f.hidden, f.width, f.height, 0 AS dirs
FROM %s AS f
WHERE %s';
$sql = sprintf($sql, $this->tbf, $whr);
if (($res = $this->query($sql))) {
while ($row = $res->fetch_assoc()) {
if ($timeout && $timeout < time()) {
$this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode($path)));
break;
}
if (!$this->mimeAccepted($row['mime'], $mimes)) {
continue;
}
$id = $row['id'];
if ($id == $this->root) {
continue;
}
if ($row['parent_id'] && $id != $this->root) {
$row['phash'] = $this->encode($row['parent_id']);
}
$row['path'] = $this->_path($id);
if ($row['mime'] == 'directory') {
unset($row['width']);
unset($row['height']);
} else {
unset($row['dirs']);
}
unset($row['id']);
unset($row['parent_id']);
if (($stat = $this->updateCache($id, $row)) && empty($stat['hidden'])) {
$result[] = $stat;
}
}
}
return $result;
}
/*********************** paths/urls *************************/
/**
* Return parent directory path
*
* @param string $path file path
*
* @return string
* @author Dmitry (dio) Levashov
**/
protected function _dirname($path)
{
return ($stat = $this->stat($path)) ? (!empty($stat['phash']) ? $this->decode($stat['phash']) : $this->root) : false;
}
/**
* Return file name
*
* @param string $path file path
*
* @return string
* @author Dmitry (dio) Levashov
**/
protected function _basename($path)
{
return (($stat = $this->stat($path)) && isset($stat['name'])) ? $stat['name'] : false;
}
/**
* Join dir name and file name and return full path
*
* @param string $dir
* @param string $name
*
* @return string
* @author Dmitry (dio) Levashov
**/
protected function _joinPath($dir, $name)
{
$sql = 'SELECT id FROM ' . $this->tbf . ' WHERE parent_id=\'' . $dir . '\' AND name=\'' . $this->db->real_escape_string($name) . '\'';
if (($res = $this->query($sql)) && ($r = $res->fetch_assoc())) {
$this->updateCache($r['id'], $this->_stat($r['id']));
return $r['id'];
}
return -1;
}
/**
* Return normalized path, this works the same as os.path.normpath() in Python
*
* @param string $path path
*
* @return string
* @author Troex Nevelin
**/
protected function _normpath($path)
{
return $path;
}
/**
* Return file path related to root dir
*
* @param string $path file path
*
* @return string
* @author Dmitry (dio) Levashov
**/
protected function _relpath($path)
{
return $path;
}
/**
* Convert path related to root dir into real path
*
* @param string $path file path
*
* @return string
* @author Dmitry (dio) Levashov
**/
protected function _abspath($path)
{
return $path;
}
/**
* Return fake path started from root dir
*
* @param string $path file path
*
* @return string
* @author Dmitry (dio) Levashov
**/
protected function _path($path)
{
if (($file = $this->stat($path)) == false) {
return '';
}
$parentsIds = $this->getParents($path);
$path = '';
foreach ($parentsIds as $id) {
$dir = $this->stat($id);
$path .= $dir['name'] . $this->separator;
}
return $path . $file['name'];
}
/**
* Return true if $path is children of $parent
*
* @param string $path path to check
* @param string $parent parent path
*
* @return bool
* @author Dmitry (dio) Levashov
**/
protected function _inpath($path, $parent)
{
return $path == $parent
? true
: in_array($parent, $this->getParents($path));
}
/***************** file stat ********************/
/**
* Return stat for given path.
* Stat contains following fields:
* - (int) size file size in b. required